2012-03-29 99 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