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

问题描述 投票:0回答: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

我希望用户能够使用这些 URL 访问该网站:

/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
参数,即使它是可选的。在我看来,这真的很难看。

有什么方法可以让路径助手自动拾取

@current_brand
吗?

或者也许是定义范围的更好方法

routes.rb

ruby ruby-on-rails-3 routes
3个回答
7
投票

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

class ApplicationController < ActionController::Base

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

end

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

有关这方面的更多信息,请参阅:default_url_options 和rails 3


4
投票

除了 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

0
投票

对于最近到达这里的人来说,这在 Rails 7.1 中发生了 改变

您现在可以在 ApplicationController 中显式将路径参数设置为 default_url_options 的子哈希

class ApplicationController < ActionController::Base  
  def default_url_options
    { path_params: { account_id: @current_account } }
  end

然后你可以简单地删除路径助手中的 account_id 参数

<%= link_to "Edit", edit_account_path %>
<%= link_to "Account Category", account_categories_path(@current_category)%>

您也可以随时覆盖默认值

<%= link_to "Edit Alt Account", edit_account_path(account_id: @alt_acct_id) %>

(如果您向 path_params 子哈希添加更多参数,这也适用于嵌套路由)

© www.soinside.com 2019 - 2024. All rights reserved.