views:

102

answers:

3

Say I have the following model:

class Information < ActiveRecord::Base
...
validates_length_of :name, :minimum=>3, :message=>"should be longer than 3 characters!"
...

What I want to have as an error is:
Information should be longer than 3 characters! (or similar)
and NOT "Information name should be longer than 3 characters!".

Two possible workarounds I've looked at:

  1. human_attribute_name method (mentioned here): doesn't work with my Rails 2.3.2. :-(
  2. directly do a information.errors.add "","..." if information.name.length < 3: however, this removes many useful properties triggered by the validated_length_of method like the special class-tags (for coloring the stuff red).

Any ideas? Thank you for your time.

+1  A: 

don't use the rails helper to make the errors, normally i have inline errors so something like:

def inline_error_block(obj, meth, prepend="", append="", klass="error error-form", &block)
  content = capture(&block)
  obj = (obj.respond_to?(:errors) ? obj : instance_variable_get("@#{obj}"))
  if obj
    errors = obj.errors.on(meth.to_s)
    if errors
      output = content_tag(:div, :class => klass) do
        content_tag(:p, "#{prepend}#{errors.is_a?(Array) ? errors.first : errors}#{append}", :class => "error-msg clearfix") + content
      end
      return concat(output)
    end
  end
  concat(content_tag(:div, content, :class => "no-error"))
end

tends to do the trick, but, it only shows one error per form field, am sure you could rearrange it to show them all, should you need to! (errors.first to errors.each).

To get the full name, just write the message with the field name as you want it displayed:

validates_length_of :name, :minimum=>3, :message=>"Information should be longer than 3 characters!"
Omar Qureshi
thanks for your help. On my system the bottom line gets displayed as: Information name Information should be longer than 3 characters! :(
jacob
is that using errors_for or using my helper?
Omar Qureshi
you're right. thanks.
jacob
+2  A: 

I suppose that you display errors through *full_messages* method, which is meant for console, not for web application use. You should use *error_message_on* or *error_messages_for* helpers instead (see documentation for more info), which allow you to customize error messages.

Example:

<%= error_message_on "information", "name", :prepend_text => 'Information ' %>
Lukas Stejskal
thanks for your help.
jacob
+1  A: 

You could always set your :message to an empty string in the model then set the :prepend_text in the view to whatever you like.

Eifion
thanks for your help
jacob