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'
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With