Rails: field names

I have a User model with an "email" field.

In my opinion, I made a shortcut for this field as "Email Address" as follows:

<%= form_for(:user) do |f| %> <%= f.label :email, 'Email address' %><br / <%= f.text_field :email %> <% end %> 

However, when verification errors are generated, "Email" is used instead:

Email is not valid

Is there something I can add to the model so that: the email always displays in the "Email Address", and not just "Email"?

Many thanks

+6
ruby-on-rails ruby-on-rails-3
source share
4 answers

Extending the gjb comments, I just added this to config / initializers / inflections.rb:

 ActiveSupport::Inflector.inflections do |inflect| inflect.human 'email', 'Email address' end 

I think this is a lot neat.

+4
source share

To do this, you do not need to rename the table columns. There is a very clean fix:

 class User < ActiveRecord::Base HUMAN_ATTRIBUTE_NAMES = { :email => 'Email address', :first_name => 'First name' } class << self def human_attribute_name attribute_name HUMAN_ATTRIBUTE_NAMES[attribute_name.to_sym] || super end end end 

What we did was create an attribute hash where we want to configure the names. You do not need to list them all, as many attribute names will work out of the box the way you want. Then we will override the ActiveRecord method human_attribute_name to try to find the name in our hash first.

This does two very cool things: you no longer need to specify custom shortcuts in your forms, and your error messages will also have new names! As a bonus, you can use these names wherever you want by calling:

 <%= User.human_attribute_name(:email) %> 

This creates a more unified approach to naming. If you want to change “email” to “email” next week, you only need to do this in one place.

Hope this helps!

+7
source share
 validates_presence_of :email, :message => "address cannot be blank" 
+1
source share

There are two ways to handle this. Rename your column to email_address or change the validation in the user model (recommended):

 validates_presence_of :email, :message => "Address cannot be blank..." 

What you need to do: "The email address cannot be empty ..." in your view.

+1
source share

All Articles