Rails路由:为路径助手提供默认值

有没有办法为url / path助手提供默认值?

我有一个可选的范围环绕我的所有路线:

#config/routes.rb Foo::Application.routes.draw do scope "(:current_brand)", :constraints => { :current_brand => /(foo)|(bar)/ } do # ... all other routes go here end end 

我希望用户能够使用以下URL访问该网站:

 /foo/some-place /bar/some-place /some-place 

为方便起见,我在ApplicationController设置了@current_brand

 # app/controllers/application_controller.rb class ApplicationController < ActionController::Base before_filter :set_brand def set_brand if params.has_key?(:current_brand) @current_brand = Brand.find_by_slug(params[:current_brand]) else @current_brand = Brand.find_by_slug('blah') end end end 

到目前为止一切顺利,但现在我必须修改所有*_path*_url调用以包含:current_brand参数,即使它是可选的。 这真是丑陋,IMO。

有什么方法可以让路径助手自动选择@current_brand

或者也许是在routes.rb定义范围的更好方法?

我想你会想做这样的事情:

 class ApplicationController < ActionController::Base def url_options { :current_brand => @current_brand }.merge(super) end end 

每次构造url时都会自动调用此方法,并将其结果合并到参数中。

有关这方面的更多信息,请查看: default_url_options和rails 3

除了CMW的回答,为了让它与rspec一起工作,我在spec/support/default_url_options.rb添加了这个hack

 ActionDispatch::Routing::RouteSet.class_eval do undef_method :default_url_options def default_url_options(options={}) { :current_brand => default_brand } end end