Hol*_*lly 6 alert locale nested-forms nested-attributes ruby-on-rails-3
我正在尝试自定义用户在错误输入数据时在窗体顶部看到的错误消息警报.我正在尝试自定义的错误消息提醒是针对嵌套形式的模型属性.
我在这里尝试过编写文件的解决方案,config/locales/en.yml
但这只会更改消息而不是错误消息之前显示的模型和属性的名称.
我也尝试过Billy在他的回答中提出的建议,结果相同.即
1个错误禁止保存这个徒步旅行车:
- 来自"我的自定义空白错误消息"的路线指示
有没有办法让我在错误消息中显示更加用户友好的模型和属性名称,或者从错误消息中完全删除它们?
这是我有的:
# 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"
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
您可以使用:message
选项来分配自定义错误消息.
例:
validates :directions_from, presence: true,
message: "'Direction from' really really really can't be blank!"
Run Code Online (Sandbox Code Playgroud)
然后,此自定义错误消息将显示<%= msg %>
在窗体视图中.
参考:http://edgeguides.rubyonrails.org/active_record_validations.html#message
添加 要回答关于评论的OP问题,即网页中显示的消息不是很友好,显示结果为"方向指示来自'方向'确实真的不能为空"
原因是视图模板用于errors.full_messages
显示错误消息.您可以使用两个选项轻松自定义它:
选项1:编写没有主题的自定义消息.即really can't be blank
选项2:像以前一样在完整句子中写入消息,但message
仅参考视图,而不是full_message
例:
<% @hikingtrail.errors.messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
Run Code Online (Sandbox Code Playgroud)
参考:http://rubydoc.info/docs/rails/3.2.8/ActiveModel/Errors(full_message
仅仅是attribute
和的混合message
)