6

ユーザーがデータを誤って入力したときにフォームの上部に表示されるエラー メッセージ アラートをカスタマイズしようとしています。カスタマイズしようとしているエラー メッセージ アラートは、ネストされた形式のモデル属性に関するものです。

ここでファイルを編集するという解決策を試しましたconfig/locales/en.ymlが、これはエラーメッセージの前に表示されるモデルと属性の名前ではなく、メッセージのみを変更します。

また、ビリーが彼の回答で提案したことも試しましたが、同じ結果が得られました。すなわち

1 つのエラーにより、このハイキング トレイルを保存できませんでした:
- 「My Custom Blank Error Message」からのルート案内

エラー メッセージに、よりユーザー フレンドリーなモデルと属性の名前を表示したり、エラー メッセージからそれらを完全に削除したりする方法はありますか?

これが私が持っているものです:

構成/ロケール/en.yml

    # Sample localization file for English. Add more files in this directory for other locales.
    # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
en:  
  activerecord:
    models: 
      direction: "In the Getting There section"
    attributes:
      direction:
        directions_from: "From field"
    errors:
      full_messages:
      format: "%{message}"
      models:
        direction:
          attributes:
            directions_from:
              blank: "My Custom Blank Error Message"

モデル

class Direction < ActiveRecord::Base
  belongs_to :hikingtrail

  attr_accessible :directions_by, :directions_desc, :directions_from

  validates :directions_from, :presence => {message: "'My Custom Error Message'", :if => Proc.new { |a| a.directions_by? || a.directions_desc? } }

  validates :directions_by, :presence => {message: "'My Custom Error Message'", :if => Proc.new { |a| a.directions_from? || a.directions_desc? } }

  validates :directions_desc, :presence => {message: "'My Custom Error Message'", :if => Proc.new { |a| a.directions_from? || a.directions_by? } }
end
4

2 に答える 2

6

オプションを使用:messageして、カスタム エラー メッセージを割り当てることができます。

例:

validates :directions_from, presence: true, 
  message: "'Direction from' really really really can't be blank!"

次に、このカスタム エラー メッセージが<%= msg %>フォーム ビューのように表示されます。

参照: http://edgeguides.rubyonrails.org/active_record_validations.html#message

追加 コメントに関するOPの質問に答えるために、つまり、Webページに表示されるメッセージはあまり友好的ではなく、結果を「「からの方向」からの方向は本当に空白にすることはできません」と表示します

errors.full_messagesその理由は、エラー メッセージを表示するために使用されるビュー テンプレートにあります。次の 2 つのオプションで簡単にカスタマイズできます。

オプション 1: 件名なしでカスタム メッセージを作成します。すなわちreally can't be blank

オプション 2: 前と同じようにメッセージを全文で書きますmessagefull_message

例:

<% @hikingtrail.errors.messages.each do |msg| %>
    <li><%= msg %></li>
<% end %>

参照: http://rubydoc.info/docs/rails/3.2.8/ActiveModel/Errors (とfull_messageの混合にすぎません)attributemessage

于 2013-03-29T01:39:36.450 に答える