我之前问过这个问题,并认为它是固定的,但事实并非如此。上一个问题在这里
我的问题是我正在尝试设置我的路线,以便当我输入时
本地主机:3000/站点/管理员
它应该重定向到
本地主机:3000/英文/站点/管理员
这是我的路线.rb 文件
scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
get "log_out" => "sessions#destroy", as: "log_out"
get "log_in" => "sessions#new", as: "log_in"
resources :sites, except: [:new, :edit, :index, :show, :update, :destroy, :create] do
collection do
get :home
get :about_us
get :faq
get :discounts
get :services
get :contact_us
get :admin
get :posts
end
end
resources :users
resources :abouts
resources :sessions
resources :coupons
resources :monthly_posts
resources :reviews
resources :categories do
collection { post :sort }
resources :children, :controller => :categories, :only => [:index, :new, :create, :new_subcategory]
end
resources :products do
member do
put :move_up
put :move_down
end
end
resources :faqs do
collection { post :sort }
end
root :to => 'sites#home'
match "/savesort" => 'sites#savesort'
end
match '', to: redirect("/#{I18n.default_locale}")
match '*path', to: redirect("/#{I18n.default_locale}/%{path}")
但截至目前,它会重定向到/en/en/sites/admin(添加 en 直到浏览器抱怨)。
有什么想法为什么它不断添加/en 吗?
编辑:答案很好,谢谢。你能帮我诊断根路由吗?
root to: redirect("#{/#{I18n.default_locale}") # handles /
我知道重定向正在寻找类似的东西
redirect("www.example.com")
所以这就剩下这部分了
#{/#{I18n.default_locale}
#{ 使用的是 rubys 字符串插值,对吧? 我不确定那个 { 在做什么。
那么我们有
/#{I18n.default_locale}
哪个还使用字符串插值并打印出I18n.default_locale的值?
希望这是有道理的,我真的很感谢你的帮助,我学到了很多东西。
编辑 2:
我将行从
root to: redirect("#{/#{I18n.default_locale}") # handles /
自
root to: redirect("/#{I18n.default_locale}") # handles /
但我不确定这是否正确。现在我收到错误
uninitialized constant LocaleController
我知道它从根目录到"locale#root"的错误,但我认为 locale# 将来自范围。
我会继续玩它,让你知道任何进展。
这是指向我的路由文件的新链接 https://gist.github.com/2332198
我们又见面了,鲁沃恩。 :)
我创建了一个测试轨道应用程序,以下最小示例对我有用:
scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
resources :sites do
collection do
get :admin
end
end
root to: "locale#root" # handles /en/
match "*path", to: "locale#not_found" # handles /en/fake/path/whatever
end
root to: redirect("/#{I18n.default_locale}") # handles /
match '*path', to: redirect("/#{I18n.default_locale}/%{path}") # handles /not-a-locale/anything
使用 Rails 4.0.x 时,重定向中%{path}
的将转义路径中的斜杠,因此您将获得一个无限循环重定向到/en/en%2Fen%2Fen%2Fen...
以防万一有人,像我一样,正在寻找适合 Rails-4 的解决方案,这就是我发现可以正常工作的方法,即使有更复杂的路径需要重定向:
# Redirect root to /:locale if needed
root to: redirect("/#{I18n.locale}", status: 301)
# Match missing locale paths to /:locale/path
# handling additional formats and/or get params
match '*path', to: (redirect(status: 307) do |params,request|
sub_params = request.params.except :path
if sub_params.size > 0
format = sub_params[:format]
sub_params.except! :format
if format.present?
"/#{I18n.locale}/#{params[:path]}.#{format}?#{sub_params.to_query}"
else
"/#{I18n.locale}/#{params[:path]}?#{sub_params.to_query}"
end
else
"/#{I18n.locale}/#{params[:path]}"
end
end), via: :all
# Redirect to custom root if all previous matches fail
match '', to: redirect("/#{I18n.locale}", status: 301), via: :all