LoginSignup
2

More than 3 years have passed since last update.

【Ruby on Rails】I18nを使っているのに中途半端に翻訳される・全く翻訳されない場合の対処法(キャッシュ対策)

Last updated at Posted at 2019-10-16

今回の問題

  • ValidationにI18nで国際化した文字列を使うと、翻訳されたり、たまにされたり、全くされなかったりする

解決方法

エラーメッセージをvalidatesメソッドに指定する際、にI18nで国際化した文字列を使用するとキャッシュされてしまうようです。

なので下記のように書いていたのを・・・

address.rb
class Address < ApplicationRecord
  validates :zip_code, format: {with: /\A[0-9]{3}-[0-9]{4}\z/, message: I18n.t('addresses.zip_code_validation')}, allow_blank: true
  validates :residence_name, length: { maximum: 250, message: I18n.t('addresses.residence_name_validation') }
end

下記のようにProcを用いれば、キャッシュされずにちゃんと翻訳されるようになりました。

address.rb
class Address < ApplicationRecord
  validates :zip_code, format: {with: /\A[0-9]{3}-[0-9]{4}\z/, message: Proc.new{ I18n.t('addresses.zip_code_validation') } }, allow_blank: true
  validates :residence_name, length: { maximum: 250, message:  Proc.new{ I18n.t('addresses.residence_name_validation') } }
end

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2