On Wed, Feb 8, 2012 at 5:50 PM, David M [email protected] wrote:
I’m using it in my user.rb model this way:
Email Maybe your email is malformed.
Which exact code are you using to “show” the error message?
Internally, the error message is only remembered as “is not valid” or
“can’t be blank” (without the attribute name, as you want to have),
but certain forms of showing the error (related to the “full_message”
function of ActiveModel errors.rb) join it by default with the attribute
name:
E.g.
$ rails c
Loading development environment (Rails 3.2.1)
1.9.3p0 :001 > o = Order.new
1.9.3p0 :002 > o.valid?
=> false
1.9.3p0 :004 > o.errors[:name]
=> [“can’t be blank”]
1.9.3p0 :005 > o.errors.full_messages
=> [“Name can’t be blank” …]
1.9.3p0 :007 > o.errors.full_messages[0]
=> “Name can’t be blank”
So, if you simply used user.errors[attribute], you would get the
error message without the attribute prepended.
If you want to have the list of all of them, code like this might help
1.9.3p0 :011 > o.errors.map{|attr, message| message}.join(’
’)
=> "can’t be blank
can’t be blank
… "
Using I18n can resolve the problem in two ways:
…/config/locales$ cat errors.yml
en:
errors:
# The default format to use in full error messages.
# format: “%{attribute} %{message}”
format: “%{message}”
activerecord:
errors:
models:
order:
attributes:
name:
blank: Please fill in the name for this order
$ rails c
Loading development environment (Rails 3.2.1)
1.9.3p0 :001 > o = Order.new
1.9.3p0 :002 > o.valid?
=> false
1.9.3p0 :003 > o.errors.full_messages
=> [“Please fill in the name for this order”, “can’t be blank”, …]
I have changed 2 things here:
-
the error message itself for the Order#name attribute for a :blank
condition is customized.
-
the default “errors.format” that is used to form the “full_message”
string is changed to only have the error message (not prepended with
the attribute).
Source code can be found here:
https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml#L4
https://github.com/rails/rails/blob/master/activemodel/lib/active_model/errors.rb#L272
HTH,
Peter
*** Available for a new project ***
Peter V.
http://twitter.com/peter_v
http://rails.vandenabeele.com
http://coderwall.com/peter_v