98

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'

4 Answers 4

207

Try this

validates :title, presence: { message: "Story title is required" }
Sign up to request clarification or add additional context in comments.

8 Comments

How do I remove the :title from the error message above? Above displays as "Title Story title is required". I want "Story title is required." Thanks.
Where has the => true gone in this answer? Is it not necessary?
@dukedave oddly enough it is not necessary. You can pass anything 'truthy' to presence.
@NotDan, link broken.
@Mayumi - You can remove the attribute name from the message by writing a manual validation and adding the error to :base, for example errors.add(:base, "Story title is required)
|
18

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>

Comments

1

A custom message for a boolean with conditionals might be:

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.