Standard ActiveRecord validation message

in testing my app I just use the validations

validates_presence_of :first_name, :last_name, :email
validates_presence_of :academy, :message => “You must select an
Academy”
validates_presence_of :role, :message => “You must select a role”

standard error_messages are fine for most of my fields , resulting
in :

5 errors prohibited this data from being saved
There were problems with the following fields:

Last name can’t be blank

Email can’t be blank

First name can’t be blank

but 2 messages are a little bit confusing :

Role You must select a role

Academy You must select an Academy

the model names are embedded into the error message… how can I
suppress them and get only the message…

You must select a role

You must select an Academy

thanks fyh

erwin

2 options I can think of:

#1 - change the message of each to “must be selected.” It’s not perfect,
but the intent of the message is clear.

#2 - define your own validations using errors.add_to_base. See here for
an example:

So, for example, you might try something like:

validate :academy_is_selected

def academy_is_selected
errors.add_to_base(“You must select an Academy”) if
self.academy.blank?
end

Yeah, sorry, I meant the model attribute and meant model.

I’m not sure how you would arrange the error messages in a specific
order like that, but you can place them alongside each field.

For example, in my app I use:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /label for/
if instance.error_message.kind_of?(Array)
%(#{html_tag}
#{instance.error_message.join(', and ')}.
)
else
%(#{html_tag}
#{instance.error_message}.
)
end
else
%(#{html_tag})
end
end

(I realize that code isn’t very neat - I wrote it a few months ago and
it’s worked fine, so I haven’t touched it since.)

And then my forms look like:

<%= f.label :name %>
<%= f.text_field :name, :size => 50 %>

<%= f.label :email %>
<%= f.text_field :email, :size => 50 %>

<%= f.label :password %>
<%= f.password_field :password, :size => 50 %>

And in my CSS file: span.validation-error{color:red}

So, whenever the form is submitted and has errors, the labels are
replaced with the error messages in red.

So this:
Email
(email text field)

becomes

Email is too short, and does not look valid
(email text field)

Anyway, that’s my solution, and I think it looks nice, but of course
feel free to be creative.

Chris H. wrote:

Yeah, sorry, I meant the model attribute and meant model.

Geez, I am not articulating myself clearly today. I meant the model
attribute and SAID model.

Thanks , I just realized that it was not the Model names, but rather
the field names in my User model… you’re right that’s fine now…

btw , is there any way to get the error messages in a sequence
similar to the textfields sequence… ?
I doubt as it’s a hash and so non-ordered , but …

Erwin

On 25 juin, 18:19, Chris H. [email protected]