u26*_*622 5 ruby routes ruby-on-rails-3
有没有办法为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
Run Code Online (Sandbox Code Playgroud)
我希望用户能够使用以下URL访问该网站:
/foo/some-place
/bar/some-place
/some-place
Run Code Online (Sandbox Code Playgroud)
为了方便起见,我设置了一个@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
Run Code Online (Sandbox Code Playgroud)
到目前为止一切都那么好,但是现在我必须修改all *_path
并*_url
调用包含:current_brand
参数,即使它是可选的.这真是丑陋,IMO.
有什么方法可以让路径助手自动接听@current_brand
吗?
或者也许是一种更好的方法来定义范围routes.rb
?
我想你会想做这样的事情:
class ApplicationController < ActionController::Base
def url_options
{ :current_brand => @current_brand }.merge(super)
end
end
Run Code Online (Sandbox Code Playgroud)
每次构造url时都会自动调用此方法,并将其结果合并到参数中.
有关这方面的更多信息,请查看:default_url_options和rails 3
除了CMW的回答,为了让它与rspec一起工作,我添加了这个hack 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
Run Code Online (Sandbox Code Playgroud)