Rails 3的验证自定义消息

Rails 引入了验证模型内部属性的新方法。 当我吸毒的时候

validates :title, :presence => true

它工作,但当我试图添加一个自定义消息

validates :title, :presence => true,:message => "Story title is required"

生成错误

Unknown validator: 'message'
54411 次浏览

Try this

validates :title, presence: { message: "Story title is required" }

Actually, I did this in a better way. If you want to remove the field title from the message you should use this on your _form.htmk.erb view:

As you can see inside this view:

<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>

Replace it by:

<ul>
<% @article.errors.each_with_index do |msg, i| %>
<li><%= msg[1] %></li>
<% end %>
</ul>

You can use HUMANIZED_ATTRIBUTES of rails 3 . For example in above case, it will be like :

HUMANIZED_ATTRIBUTES = {
:title => "story"
}
def self.human_attribute_name(attr, options={})
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end

It will give you error message, replacing model attribute title with story.

A custom message for a boolean with conditionals might be:

validates :foo,  inclusion: { in: [true, false], message: "cannot be blank" }, if: :bar?