问题
My routes.rb
MyApp::Application.routes.draw do
scope '(:locale)' do
#all resources here
end
namespace :blog do
resources :posts, :only => [:index, :show]
end
end
My application_controller.rb
class ApplicationController < ActionController::Base
#
#
before_filter :set_locale
private
def default_url_options(options = {})
{locale: I18n.locale}
end
def set_locale
#code for detect locale here
end
#
#
end
All the resources inside scope '(:locale)'
is working fine.
However I don't want use locale with namespace :blog
and when I try click on blog links I can see this url http://localhost:3000/blog/posts?locale=en
How can I remove locale of namespace :blog...
and blog resource
?. I want get a url something like http://localhost:3000/blog/posts
I want to remove the ?locale=en
Thanks!
回答1:
Use skip_before_filter
in your Blog controllers?
回答2:
Given what you said in the comments, try only including the locale
in your default_url_options
if the current controller is not the PostsController
, which would hopefully get rid of the trailing?locale=en
issue. Perhaps something like:
def default_url_options(options = {})
{ locale: I18n.locale } unless controller_name == 'posts'
end
Or, since default_url_options is depreciated, if you want to use url_options
, perhaps something like:
def url_options
controller_name == 'posts' ? super : { locale: I18n.locale }.merge(super)
end
Neither of the above tested, so I'm not sure either of them will work.
Edit
How about if you set the locale
to nil
like in this StackOverflow Q&A? So maybe something like:
def url_options
locale = controller_name == 'posts' ? nil : I18n.locale
{ locale: locale }.merge(super)
end
来源:https://stackoverflow.com/questions/15767715/before-filter-set-locale-except-controller