before_filter set_locale除了控制器

时间:2013-04-02 15:12:39

标签: ruby-on-rails ruby ruby-on-rails-3 internationalization ruby-on-rails-3.2

我的routes.rb

MyApp::Application.routes.draw do
 scope '(:locale)' do
  #all resources here
 end
 namespace :blog do
  resources :posts, :only => [:index, :show]
 end
end

我的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

scope '(:locale)'内的所有资源都运行良好。

但是我不想在namespace :blog 中使用区域设置,当我尝试点击博客链接时,我可以看到此网址http://localhost:3000/blog/posts?locale=en

如何删除namespace :blog...blog resource的区域设置?我希望获得类似http://localhost:3000/blog/posts 的网址我想删除?locale=en

谢谢!

2 个答案:

答案 0 :(得分:1)

在博客控制器中使用skip_before_filter

答案 1 :(得分:0)

根据您在评论中所说的内容,如果当前控制器不是locale,请尽量在default_url_options中包含PostsController,这样可以摆脱尾随< /> ?locale=en问题。也许是这样的事情:

 def default_url_options(options = {})
   { locale: I18n.locale } unless controller_name == 'posts'
 end

或者,自default_url_options is depreciated起,如果您想使用url_options,可能会这样:

def url_options
  controller_name == 'posts' ? super : { locale: I18n.locale }.merge(super)
end

以上都没有测试过,所以我不确定它们中的任何一个都能正常工作。

修改

如果您在this StackOverflow Q&A中将locale设置为nil,怎么样?所以可能是这样的:

def url_options
  locale = controller_name == 'posts' ? nil : I18n.locale
  { locale: locale }.merge(super)
end