LoginSignup
1
1

More than 3 years have passed since last update.

Railsで多言語化対応する!

Posted at

自分が開発しているwebアプリを英語に対応しようとしたときにやったことを書いていきます。

詳しくは>

インストール

Gemfile
gem 'rails-i18n'

インストール

bundle

config/application.rbに設定

config/application.rb
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]

    # 対応する言語。今回は日本語(ja)と英語(en)だけ
    config.i18n.available_locales = %i(ja en)

    # 上記の対応言語以外の言語が指定された場合、エラーとするかの設定
    config.i18n.enforce_available_locales = true

    # デフォルトの言語
    config.i18n.default_locale = :ja

controller

controller/application_controller.rb
    before_action :set_locale

    def set_locale
        I18n.locale = locale
    end

    def locale
        @locale ||= params[:locale] ||= I18n.default_locale
    end

    def default_url_options(options={})
        options.merge(locale: locale)
    end

routes.rb

routes.rb
  scope '(:locale)', locale: /#{I18n.available_locales.map(&:to_s).join('|')}/ do
    root "posts#index"
    resources :posts
  end

scopeで囲んだ部分が多言語対応するページです。

多言語化

en.ymlとja.ymlを作ります。
多言語化したい文に

views
<%= t(:hello) %>

と書きます。helloのところは自由に変えてください

ja.yml
  ja:
    hello: こんにちは
      # モデルは全て activerecord を起点にする。
      # これにより、User.model_name.human / User.human_attribute_name({attr_name})でアクセス可能。
    activerecord:
      models:
        user: 'ユーザー情報'
      attributes:
        user:
          name: '名前'
          mail: 'メールアドレス'
          url:  'ウェブページ'
en.yml
  en:
     hello: "hello"
    # モデルは全て activerecord を起点にする。
      # これにより、User.model_name.human / User.human_attribute_name({attr_name})でアクセス可能。
    activerecord:
      models:
        user: 'User'
      attributes:
        user:
          name: 'Name'
          mail: 'Email'
          url:  'URL'

こんな感じでやっていきます。

参考
http://alfa.hatenablog.jp/entry/2013/12/03/221308

1
1
0

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
1
1