プログラミングを完全に理解したエンジニアのメモ

チラ裏レベルのことしか書いてないインターネットの藻屑

Railsで多言語対応する

トップページを多言語化するサンプルコードのメモ

Gemfile

gem 'rails-i18n'
gem 'http_accept_language'

config/routes.rb

Rails.application.routes.draw do
  scope '(:locale)', locale: /#{I18n.available_locales.join('|')}/ do
    root 'top#index'
  end
end

config/application.rb

require_relative 'boot'
require 'rails/all'

Bundler.require(*Rails.groups)

module CwSystem
  class Application < Rails::Application
    config.load_defaults 5.1
    config.i18n.available_locales = %i(ja en fr es pt)
    config.i18n.enforce_available_locales = true
    config.i18n.default_locale = :ja
  end
end

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :set_locale

  def set_locale
    I18n.locale = locale
  end

  def locale
    @locale ||= params[:locale] || I18n.default_locale || http_accept_language.compatible_language_from(I18n.available_locales || I18n.default_locale)
  end

  def default_url_options
    return {} if params[:local].blank?
    {locale: locale}
  end
end

app/helpers/application_helper.rb

module ApplicationHelper
  def i18n_url_for(options)
    if options[:locale] == I18n.default_locale
      options[:locale] = nil
    end
    url_for(options)
  end
end

config/locales/

それぞれの言語のymlを作成