bookcasey
bookcasey

Reputation: 40453

Error Messages should Match Labels

I have a form. Many of the labels need to have a different name than they are given in the model.

attr_accessible :pin

Simpleform view:

= f.input :pin, :label => "Secret Code"

When validation fails, the error uses the model's name for the field ("Pin"), rather than the label I set in the view ("Secret Code"). The user will be confused on what field has the error.

Currently I have a helper that changes the label:

def fix_pin_errors(msg)
  msg.gsub!('Pin', 'Secret Code')
end

If I am doing this for many fields, however, it becomes tedious and not DRY.

What is the best way to have errors match labels that differ from the names the model gives them?

Upvotes: 1

Views: 321

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

I18n is your friend. Read this guide. It will explain how to globally convert these so they get picked up everywhere you need.

For your example, it might look something like this:

In en.yml:

en:
  activerecord:
    attributes:
      your_model_name:
        pin: 'Secret Code'

Upvotes: 3

Related Questions