有什么方法可以为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
?
由于加入这个技巧。这是我最终选择的解决方案。我们还有很多问题,例如需要在邮件程序中设置它,以及使用rspec工作的黑客(粘贴在我自己的答案中) – u2622 2012-04-07 19:04:58
哦,是的,我很抱歉没有指出这一点。很高兴你提到它的完整性。 – CMW 2012-04-08 18:35:08