Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 341
David Unric Avatar asked Sep 11 '25 13:09

David Unric


1 Answers

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]
like image 143
zwippie Avatar answered Sep 14 '25 01:09

zwippie