2012-03-29 103 views
5

有什么方法可以为url /路径助手提供默认值吗?Rails路由:为路径助手提供默认值

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

#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

回答

8

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

class ApplicationController < ActionController::Base 

    def url_options 
    { :current_brand => @current_brand }.merge(super) 
    end 

end 

此方法是自动调用每次URL构造和它的结果将合并到的参数。

有关此更多的信息,看:default_url_options and rails 3

+0

由于加入这个技巧。这是我最终选择的解决方案。我们还有很多问题,例如需要在邮件程序中设置它,以及使用rspec工作的黑客(粘贴在我自己的答案中) – u2622 2012-04-07 19:04:58

+0

哦,是的,我很抱歉没有指出这一点。很高兴你提到它的完整性。 – CMW 2012-04-08 18:35:08

5

除了CMW的回答,得到它与rspec的工作,我在spec/support/default_url_options.rb

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