简体   繁体   中英

validation custom message for rails 3

Rails has introduced new way to validate attributes inside model. When I use

validates :title, :presence => true

it works but when I try to add a custom message

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

an error is generated

Unknown validator: 'message'

试试这个

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>

具有条件的布尔值的自定义消息可能是:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM