Home > Net >  Way to change locale on rails validation messages
Way to change locale on rails validation messages

Time:01-12

Ruby 3.1.3, rails 7.0.4

I have a simple uniqueness validation in model:

app/models/user.rb

validates :email, uniqueness: true

app/controllers/user_controller.rb

user = User.new
user.email = '[email protected]'
user.save

config/locales/en-US.yml

en-US:
  activerecord:
    attributes:
      user:
        email: email
  errors:
    format: "%{attribute} %{message}"
    messages:
      taken: has already been taken

config/locales/ja-JP.yml

ja-JP:
  activerecord:
    attributes:
      user:
        email: メールアドレス
  errors:
    format: "%{attribute} %{message}"
    messages:
      taken: はすでに存在します。

When I tried to create a user with existed email to try to get the error message it automatically gave me the english version of the error message, which is

email has already been taken

Even though the default language is japanese (I18n.default_locale = :ja-JP). How do I change the locale dynamically when creating the user in controller? Something like

user.save(lang: 'ja-JP')
return user.errors.full_messages => this should output ["メールアドレス はすでに存在します"]

user.save(lang: 'en-US')
return user.errors.full_messages => this should output ["email has already been taken"]

How does rails decide what language to use? I have not set the locale anywhere in controller.

CodePudding user response:

Try below

ja-JP:
  activerecord:
    errors:
      models:
        user:
          attributes:
            email:
              blank: メールアドレス
              invalid: メールアドレス

Dynamic: In the below example dynamic variable value is passed to set locales.

Controller or helper code:

message = t('coupons.redeemed_html', count: coupon.redemptions_count, limit: limit)

locales file:

jp:
 coupons:
   redeemed_html:
     zero: <span >Not yet</span>
     one: '%{count}/<span >%{limit}</span>'
     other: '%{count}/<span >%{limit}</span>'

CodePudding user response:

with_locale should do the trick.

# app/controllers/user_controller.rb

I18n.with_locale(:en) do
  ...
  user.save
end

Note that the fact that your I18n.default_locale is set to jp, but the error you receive is still in English suggests that you're also setting I18n.locale = ... somewhere in the code.

  • Related