【发布时间】:2012-03-29 18:41:49
【问题描述】:
有没有办法为 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 中定义范围的更好方法?
【问题讨论】:
标签: ruby ruby-on-rails-3 routes