Re: standard ActiveRecord validation message

Chris Hanks
Thu, 25 Jun 2009 16:43:57 -0000

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.

http://guides.rails.info/activerecord_validations_callbacks.html#customizing-the-error-messages-html

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.