例えば、こんな感じでRESTFULなURLでロケール情報を渡したい。
controllerを修正します。
default_url_optionsの設定は、全てのリンクに自動的にロケールを追加するためです。
vi app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :detect_locale
  def default_url_options(options = {}) 
    { :locale => I18n.locale }
  end 
private
  def detect_locale
    I18n.locale = params[:locale]
  end 
end
ルーティングも変更します。
vi config/routes.rb
今までのroutingをscopeで囲みます。
scope "/:locale" do
  devise_for :users
  namespace :admin do
    resources :users
  end
end
match '/:locale' => 'home#index'
root :to => 'home#index'
切り替えるスイッチはこんな感じで。
  <% if params[:locale] == "ja" %>
    <%= link_to(t("general.en"), root_path(:locale => "en")) %>
  <% elsif params[:locale] == "en" %>
    <%= link_to(t("general.ja"), root_path(:locale => "ja")) %>
  <% end %>
 
0 件のコメント:
コメントを投稿