Rails I 18 nの基本-エラー、モデル、および属性を翻訳する


ヘッダー写真@joaosilas
この投稿はまたスペイン語に翻訳されていますIbidem Group . <研究ノート> Etpa - en - ol - Aqu -https://www.ibidemgroup.com/edu/traducir-rails-i18n/
I 18 N (国際化) APIはRailsのローカライズをサポートする標準的な方法です.職員guide 必要なすべての情報がありますが、それはまた非常に長いです.このポストは、私が最初にI 18 Nをセットアップする方法を学んでいたとき、私が取ったメモに基づきます、そして、私のゴールはより接近しているチュートリアルを提供することになっています.このポストは、エラーメッセージとモデル名/属性名、およびI18n.t メソッド.

なぜ、私はこのポストを書きましたか
i 18 nへの私の最初の露出はrails-i18n GEMは、一般的に使用されるエラーメッセージ、曜日などのデフォルトの翻訳を提供します.この宝石をインストールして一日呼び出すことができます.
  • あなたはRails - I 18 Nが提供するものとは異なる翻訳を使用したい
  • あなたはレールで覆われていない言語を含めたい
  • あなたはいくつかの言語の翻訳を必要とし、言語の数十を含む全体の宝石をインストールする必要はありません
  • 私の場合、それは第3の理由でした-私は日本語の翻訳を必要としました.

    目次
  • 0. Setting your default locale

  • 1. Translating model and attribute names
  • 1.1 Defining your translations
  • 1.2 Accessing model and attribute translations

  • 2. Translating ActiveRecord errors
  • 2.1 Error message breakdown
  • 2.2 Defining your translations

  • 0 .デフォルトのロケールの設定

    I set mine to Japanese.

    # config/application.rb
    config.i18n.default_locale = :ja
    

    モデルと属性名の翻訳 Docs: https://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

    あなたの翻訳を定義する1.1

    First, define translations for your model names and attributes in a YAML file like below. This example is for a User model with two attributes.

    # config/locales/ja.yml
    ja:
      activerecord:
        models:
          user: 'ユーザ' # <locale>.activerecord.models.<model name>
        attributes:
          user:
            name: '名前' # <locale>.activerecord.attributes.<model name>.<attribute name>
            password: 'パスワード'
    

    1.2モデルと属性翻訳にアクセスする
    # How to look up translations for model names
    User.model_name.human
    => "ユーザ"
    
    # How to look up translations for attributes (you can use symbols or strings)
    User.human_attribute_name('name')
    => "名前"
    
    User.human_attribute_name(:name)
    => "名前"
    

    ActiveRecordエラーの翻訳 Docs: https://guides.rubyonrails.org/i18n.html#error-message-scopes

    2.1エラーメッセージ故障

    Translating error messages is a bit more complicated than models. Let's talk about the error message structure first. ActiveRecord has some built-in validation errors that are raised if your record is invalid. Consider this example:

    class User < ApplicationRecord
      validates :name, presence: true
    end
    

    If your locale is :en , this error message is returned when you try to create an invalid record.

    User.create!(name: '')
    => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
    

    This message actually consists of a few parts.


    1 .ActiveRecord::RecordInvalid:エラーの種類です.いいえ翻訳が必要です.

    2 .Validation failed:この説明RecordInvalid 英語のエラー、Rails Gemのen.yml ( source code ). 翻訳はロケールに必要です.

    3 .Name can't be blankこれは違反する記録のエラーメッセージですpresence: true . それは2つの部分から成りますName とメッセージcan't be blank ( source code ). デフォルトのエラーメッセージ形式は2つの要素の補間です."%{attribute} %{message}" ( source code ). 翻訳はロケールに必要です.
    注:attribute を参照してください.翻訳がないならば、Railsは英語で属性名を印刷します.
    ロケールを変更する場合はどうなりますか:en to :ja 対応する翻訳を定義せずに?エラーメッセージはtranslation missing .
    User.create!(name: '')
    # => ActiveRecord::RecordInvalid: translation missing: ja.activerecord.errors.messages.record_invalid
    
    では、次に翻訳の提供方法を見てみましょう.

    2.2翻訳を定義する According to the official guide , Railsがあなたの誤りのために翻訳を見つけるために見るいくつかの場所があります、この順序で.
    • activerecord.errors.models.[model_name].attributes.[attribute_name]
    • activerecord.errors.models.[model_name]
    • activerecord.errors.messages
    • errors.attributes.[attribute_name]
    • errors.messages

    これは、モデル固有の属性や属性固有のエラーメッセージを設定する場合は、あまりにも行うことができます.しかし、この場合、我々はrecord_invalid and blank モデルにかかわらず同じように翻訳される.以下にサンプルの設定を示します:
    # config/locales/ja.yml
    
    ja:
      activerecord:
        errors:
          messages:
            record_invalid: 'バリデーションに失敗しました: %{errors}'
      errors:
        format: '%{attribute}%{message}'
        messages:
          # You should also include translations for other ActiveRecord errors such as "empty", "taken", etc.
          blank: 'を入力してください'
    

    アバウトrails-i18n 宝石
    上記の設定は ja.yml ファイル名rails-i18n 私がイントロで言及した宝石.この宝石のインストールは、デフォルトの翻訳を設定する簡単な方法です.それはあなたのRailsプロジェクトであらかじめインストールされていないので、チェックしてくださいdocumentation インストールと使用方法の詳細については.

    2.3あなたの翻訳にアクセスすることI18n.t

    Now that you've provided translations for error messages, Rails will actually print the error messages instead of translation missing .

    The next question is, how can you look up the translations you defined? For example, what if you want to assert that some message is being raised in a test?

    test 'user is invalid if name is blank' do
      invalid_user = User.new(name: '')
      assert invalid_user.errors.messages[:name].include?(<cannot be blank message>)
    end
    

    This is where the very convenient I18n.t method comes in. The t stands for "translate", and it allows you to access any translation defined in your YAML files. For this example, we want to access the errors.messages.blank message (refer to 2.2 for the YAML file). There are two ways to do this.

    I18n.t('errors.messages.blank')
    # => "を入力してください"
    
    I18n.t('blank', scope: ['errors', 'messages'])
    # => "を入力してください"
    

    Just like that, you can look up any translation you've defined!

    Note: You can look up model names and attribute names without using the human method too, like I18n.t('activerecord.models.user') .

    test 'user is invalid if name is blank' do
      invalid_user = User.create(name: '')
      expected_error = I18n.t('errors.messages.blank')
      assert invalid_user.errors.messages[:name].include?(expected_error)
    end
    

    2.4文字列補間によるエラーの検索 https://guides.rubyonrails.org/i18n.html#error-message-interpolation
    あなたが中でYAMLファイルのどれかを見るならばrails-i18n GEMは、いくつかのメッセージが文字列補間を使用することに気づくかもしれません.たとえば、検証エラーメッセージがgreater_than , あなたは言いたいmust be greater than %{count} , そして、count . Railsは実際のエラーが発生したときにあなたのために入力されますが、どのように我々はcount エラーメッセージを調べるときにI18n.t ?
    I18n.t('errors.messages.greater_than')
    # => "は%{count}より大きい値にしてください"
    
    引数として渡すだけです.
    I18n.t('errors.messages.greater_than', count: 5)
    # => "は5より大きい値にしてください"
    
    私はこれがあなたがレールでi 18 nですることができるすべてをカバーするのに近寄っていないということを知っています、しかし、私はそれが役に立つ導入を提供することを望みます.読書ありがとう!