Rails路由:为路径助手提供默认值 [英] Rails routing: Giving default values for path helpers
问题描述
是否可以通过某种方式为url / path帮助器提供默认值?
Is there some way to provide a default value to the url/path helpers?
我在所有路由中都有一个可选范围:
I have an optional scope wrapping around all of my routes:
#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访问网站:
I want users to be able to access the site using these URLs:
/foo/some-place
/bar/some-place
/some-place
为方便起见,我在 ApplicationController
中设置了 @current_brand
:
For convenience, I'm setting up a @current_brand
in my 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,这真的很丑。
So far so good, but now I must modify all *_path
and *_url
calls to include the :current_brand
parameter, even though it is optional. This is really ugly, IMO.
有什么方法可以使帮助者自动找到 @current_brand
?
Is there some way I can make the path helpers automagically pick up on @current_brand
?
还是在 routes.rb
中定义范围的更好方法?
Or perhaps a better way to define the scope in routes.rb
?
推荐答案
我认为您会想要执行以下操作:
I think you will want to do something like this:
class ApplicationController < ActionController::Base
def url_options
{ :current_brand => @current_brand }.merge(super)
end
end
每次构造url并将其结果合并到参数中时,都会自动调用此方法。
This method is called automatically every time url is constructed and it's result is merged into the parameters.
有关此的更多信息,请参见: default_url_options和rails 3
For more info on this, look at: default_url_options and rails 3
这篇关于Rails路由:为路径助手提供默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!