开发者

validation custom message for rails 3

开发者 https://www.devze.com 2023-02-18 17:34 出处:网络
Rails has introduced new way to validat开发者_开发技巧e attributes inside model. When I use validates :title, :presence => true

Rails has introduced new way to validat开发者_开发技巧e 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'


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>


A custom message for a boolean with conditionals might be:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消