JBlake
JBlake

Reputation: 1064

Prettier error messages for Rails nested attributes?

Take my order checkout process for example,

Order belongs to guest

guest belongs to user

user has many phone numbers

number is an attribute on phone number.

I'll get error messages like this:

[:"guest.user.phone_numbers.number", "is an invalid number"]

How do I go about returning a prettier message? Something like, 'Invalid phone number format.' or 'Phone number is invalid'

I realize I could hack it out of the string, but I'm hoping for a Rails Way of defining the association names or something? with I18n support?

Upvotes: 0

Views: 200

Answers (1)

max
max

Reputation: 102174

In the event you need to access nested attributes within a given model, you should nest these under model/attribute at the model level of your translation file:

en:   
  activerecord:
    attributes:
     user/gender:
       female: "Female"
       male: "Male"

Then User.human_attribute_name("gender.female") will return "Female".
- Rails Guides - Translations for Active Record Models

en:
  activerecord:
    attributes:
      guest/user/phone_numbers:
        number: 'Phone number'

Upvotes: 1

Related Questions