Last active
July 12, 2017 09:47
-
-
Save koki-h/437ff4d0f2eea46225a0973c51057cde to your computer and use it in GitHub Desktop.
複数項目が関連するエラーを発生させた時、メッセージは1つで良いが複数項目に色をつけたい場合は app/models/ 配下を以下のようにする。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ApplicationRecord < ActiveRecord::Base | |
| self.abstract_class = true | |
| # Validationエラーの時、メッセージは出したくないが、フィールドに色はつけたいので | |
| # errors.add()でメッセージ部分にnilを入れた時はfull_messagesでメッセージが返らないようにした。 | |
| class ActiveModel::Errors | |
| def full_messages | |
| map { |attribute, message| full_message(attribute, message) if message }.delete_if{|message| message.nil?} | |
| end | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Sample < ApplicationRecord | |
| validates :multipul_column_error | |
| def multipul_column_error | |
| errors.add(:col1, "とcol2がおかしいです") | |
| errors.add(:col2, nil) | |
| end | |
| end | |
| #以上のようにすると View側で@sample.errors.full_messagesでは ["col1とcol2がおかしいです"]と言う結果が得られ、 | |
| # f.text_field(:col1)とf.text_field(:col2)の両方が class="field_with_errors"なフィールドを生成する。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment