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

时间:2012-03-29 18:41:50

标签: ruby ruby-on-rails-3 routes

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

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

#config/routes.rb
Foo::Application.routes.draw do

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

end

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

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

为方便起见,我在@current_brand

中设置ApplicationController
# 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中定义范围的更好方法?

2 个答案:

答案 0 :(得分:8)

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

class ApplicationController < ActionController::Base

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

end

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

有关详细信息,请查看:default_url_options and rails 3

答案 1 :(得分:5)

除了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
相关问题