David Unric
David Unric

Reputation: 7719

ActiveModel::Errors translate attribute part of error message?

Looking for a solution how to write translation record in I18n yml file for the following case:

class SomeClass < ActiveRecord::Base
  validate: stock_avail

  def stock_avail
    # errors is an instance of ActiveModel::Errors
    errors.add(:quantity, I18n.t('validation.stock_exceeded'))
    # how to write a translation for :quantity part ?
  end
end

errors.add is documented here.

How and where can I write translation for :quantity attribute of error message ?

Thanks.

Upvotes: 4

Views: 2010

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33943

This is an addon to @zwippie's answer...

Now I wonder if the custom validation message could also be stored in this file.

Yes, this is under errors/messages like so:

nl:
  activerecord:
    models:
      product: Product
  attributes:
    product:
      name: Naam
      quantity: Aantal
  errors:
    messages:
      stock_exceeded: voorraad overschreden # HERE
      

So the error.add would be:

errors.add(:quantity, :stock_exceeded)

Upvotes: 0

zwippie
zwippie

Reputation: 15550

If it is about the attributes names of your model, you can add translations to config/locales/models/model_name/lang.yml.

For example, the contents of config/locales/models/product/nl.yml could be something like:

nl:
  activerecord:
    models:
      product: Product
    attributes:
      product:
        name: Naam
        quantity: Aantal

Now I wonder if the custom validation message could also be stored in this file.

Also, add this to config/application.rb:

# Load locale files in nested dictionaries
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]

Upvotes: 3

Related Questions