4

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.

David Unric
  • 7,421
  • 1
  • 37
  • 65

2 Answers2

3

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]
zwippie
  • 15,050
  • 3
  • 39
  • 54
0

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)
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64