validation custom message for rails 3

Ruby on-RailsRubyRuby on-Rails-3ValidationActiverecord

Ruby on-Rails Problem Overview


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'

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Try this

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

Solution 2 - Ruby on-Rails

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>

Solution 3 - Ruby on-Rails

A custom message for a boolean with conditionals might be:

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

Solution 4 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrabesh ShresthaView Question on Stackoverflow
Solution 1 - Ruby on-RailsShivView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMateusgfView Answer on Stackoverflow
Solution 3 - Ruby on-RailsstevenspielView Answer on Stackoverflow
Solution 4 - Ruby on-RailsShyamkkhadkaView Answer on Stackoverflow