How to set display name for field in Rails

Can I set a display name for a database field instead of using an automatically generated one?

I have a bbe_date field, and on the screens I use 'Best Before' as the displayed string. I looked through several views manually, but is there a better way?

This, we hope, takes effect wherever the field name is sent to the browser in a form convenient for humans. I especially think about validation errors (since there is a bit that I have not yet processed manually!) - my verification code does:

 record.errors.add :bbe_date, 'not valid' 

but unless I specifically intercepted this, I just see that "Bbe Date is not valid" as a validation error.

+7
source share
2 answers

You need internationalization (I18N) . Yes, even if you just want English.

Modify config / locales / en.yml and set:

 en: activerecord: attributes: your_lower_case_model_name: bbe_date: Best Before 
+13
source

One way to do this is to override the behavior of human_attribute_name , which gives the default display name. In your model:

 HUMANIZED_ATTRIBUTES = { :bbe_date => "Best Before" } def self.human_attribute_name(attr, options={}) HUMANIZED_ATTRIBUTES[attr.to_sym] || super end 

Note that if this is Rails 2, you need to remove the param parameter from the name of the directory_ person.

0
source

All Articles