我对Rails相当新,并且无法弄清楚我做错了什么 想知道是否有人可以提供帮助? 我有一个没有问题的Rails应用程序,这是在我开始修改以使其多语言之前。
为了使其多语言,我采取了以下步骤:
我将此添加到路由文件中:
范围"(:locale)",:locale => / en |是/ do
路由文件:
PropertyEvaluator::Application.routes.draw do
scope "(:locale)", :locale => /en|is/ do
root :to => "pages#home"
get 'pages/about'
get 'pages/home'
get "log_out" => "sessions#destroy", :as => "log_out"
get "log_in" => "sessions#new", :as => "log_in"
get "sign_up" => "users#new", :as => "sign_up"
resources :searches, :only => [:index, :new, :create]
resources :users, :only => [:index, :new, :create, :edit, :update, :destroy]
resources :sessions, :only => [:new, :create, :destroy]
resources :password_resets, :only => [:new, :create, :edit, :update]
resources :email_activations, :only => [:edit]
resources :roles, :only => [:edit, :update]
end
end
修改前的路由文件:
PropertyEvaluator::Application.routes.draw do
root :to => "pages#home"
get 'pages/about'
get 'pages/home'
get "log_out" => "sessions#destroy", :as => "log_out"
get "log_in" => "sessions#new", :as => "log_in"
get "sign_up" => "users#new", :as => "sign_up"
resources :searches, :only => [:index, :new, :create]
resources :users, :only => [:index, :new, :create, :edit, :update, :destroy]
resources :sessions, :only => [:new, :create, :destroy]
resources :password_resets, :only => [:new, :create, :edit, :update]
resources :email_activations, :only => [:edit]
resources :roles, :only => [:edit, :update]
end
到application_controller.rb我添加了
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
Rails.application.routes.default_url_options[:locale]= I18n.locale
对于我添加的观点:
<%= link_to_unless I18n.locale == :is, "IS", locale: :is %>
|
<%= link_to_unless I18n.locale == :en, "EN", locale: :en %>
原始路由文件正在按预期工作,但是当我将范围添加到路由文件时,问题就开始了。
我收到以下错误:
No route matches {:action=>"edit", :controller=>"users", :format=>nil, :id=>nil, :locale=>#<User id: 2, email: "bjarni.sigurdsson@bodeind.is", password_hash: "$2a$10$WzcoB5pES3TXYbWpe7xtB.yKFnqi.dhQgMXOp8/nyKi...", password_salt: "$2a$10$WzcoB5pES3TXYbWpe7xtB.", created_at: "2014-09-30 15:20:38", updated_at: "2014-10-01 12:41:57", name: "Bjarni Sigurðsson", auth_token: "wY2cfwk-1R7fSjCvqQPaWQ", password_reset_token: nil, password_reset_sent_at: nil, admin: true, email_confirmed: true, email_activation_token: nil, email_confirmed_at: "2014-09-30 15:20:38", role: 4>} missing required keys: [:id]
在视图中指向以下代码:
<%= link_to(t('views.shared.navbar.edit_user_profile'), edit_user_path(current_user), class: 'btn btn-primary') %>
如果我从路由文件中删除作用域,则可以正常工作,但所选的区域设置不会显示在网址中。
有人可以帮忙吗?
答案 0 :(得分:0)
除了路径生成时传递:locale
参数,一切都很好。看看例外情况,有::locale=>#<User...
。由于params[:locale]
为nil
,因此将用户视为第一个arg。使用以下内容扩展您的app控制器:
def default_url_options(options={})
{ locale: I18n.locale }
end