Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' 
like image 768
Prabesh Shrestha Avatar asked Mar 22 '11 04:03

Prabesh Shrestha


People also ask

How does validation work in Rails?

Before saving an Active Record object, Rails runs your validations. If these validations produce any errors, Rails does not save the object. After Active Record has performed validations, any errors found can be accessed through the errors instance method, which returns a collection of errors.

What is Validates_presence_of?

validates_presence_of(*attr_names) public. Validates that the specified attributes are not blank (as defined by Object#blank?), and, if the attribute is an association, that the associated object is not marked for destruction. Happens by default on save.

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


2 Answers

Try this

validates :title, presence: { message: "Story title is required" } 
like image 157
Shiv Avatar answered Sep 20 '22 06:09

Shiv


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> 
like image 26
Mateusgf Avatar answered Sep 18 '22 06:09

Mateusgf