【问题标题】:Rails routing: Giving default values for path helpersRails 路由:为路径助手提供默认值
【发布时间】: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


    【解决方案1】:

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

    class ApplicationController < ActionController::Base
    
      def url_options
        { :current_brand => @current_brand }.merge(super)
      end
    
    end
    

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

    有关这方面的更多信息,请查看:default_url_options and rails 3

    【讨论】:

    • 谢谢。这是我最终采用的解决方案。我们也有很多陷阱,例如需要在邮件中进行设置,以及让它与 rspec 一起使用的 hack(粘贴在我自己的答案中)
    • 哦,是的,很抱歉没有指出这一点。很高兴你提到它的完整性。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-04-02
      • 2015-03-14
      • 1970-01-01
      • 2011-10-05
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      相关资源
      最近更新 更多