【问题标题】:default_url_options and rails 3default_url_options 和 rails 3
【发布时间】:2011-08-31 08:27:53
【问题描述】:

由于 ActionController::Base#default_url_options 已弃用,我想知道如何在 rails3 中设置默认 url 选项。默认 url 选项不是静态的,而是依赖于当前请求。

http://apidock.com/rails/ActionController/Base/default_url_options

谢谢, 科林

【问题讨论】:

标签: ruby-on-rails-3 actioncontroller


【解决方案1】:

要为当前请求设置 url 选项,请在控制器中使用类似这样的内容:

class ApplicationController < ActionController::Base

  def url_options
    { :profile => current_profile }.merge(super)
  end

end

现在,:profile => current_profile 将自动合并到路径/url 参数。

路由示例:

scope ":profile" do
  resources :comments
end

只写:

comments_path

如果 current_profile 已将 to_param 设置为 'lucas':

/lucas/comments

【讨论】:

  • 谢谢!这是“官方”的 rails 3.0/3.1 方式吗?
  • 太糟糕了,当它被声明为 protected 时会抛出一个异常,这是必须的(否则它会被暴露为一个动作)。所以它不起作用。
  • 它在实际项目中对我有用,我不知道你为什么认为它作为一个动作公开,只需从你的路由中删除默认路由 /:controller/(:action) 。此方法必须是公开的。
  • 它也适用于邮件程序,只需在 ActionMailer::Base 的子类中定义方法即可:)
  • 如何根据模型属性设置选项。例如,将:profile 设置为comment.user.city_name,那么我们得到/newyork/comments/123?
【解决方案2】:

我相信首选的方法是现在告诉路由器处理这个问题:

Rails.application.routes.default_url_options[:foo]= 'bar' 

您可以将此行放入routes.rb 或初始化程序中。无论您喜欢哪个。如果值根据您的环境发生变化,您甚至可以将其放入您的环境配置中。

【讨论】:

  • 但是我怎样才能让它依赖于当前的请求,例如访问实例变量?
  • 是的,它不是线程安全的。我是通过自定义方法和 Thread.current
  • 看起来这就是 Rails 3.2 的版本。
  • 愚蠢的问题:你在哪里这行?在 routes.rb 中?在初始化程序中?
  • 如果你必须在配置级别设置这个,你如何传递一个动态的account_id?例如scope '/:account_id' - 如何在配置级别动态设置account_id
【解决方案3】:

该 apidock.com 链接具有误导性。 default_url_options 未被弃用。

http://guides.rubyonrails.org/action_controller_overview.html#default_url_options

【讨论】:

  • 我认为指南已经过时,而不是 apidoc。该方法在 Rails 3.2 中不再有效。
【解决方案4】:

对于 Rails 3,规范的做法是在 ApplicationController 中添加 default_url_options 方法。

class ApplicationController < ActionController::Base
  def default_url_options
    {
        :host => "corin.example.com",
        :port => "80"  #  Optional. Set nil to force Rails to omit
                       #    the port if for some reason it's being
                       #    included when you don't want it.
    }
  end
end

我只需要自己解决这个问题,所以我知道它有效。

本文改编自 Rails 3 指南:
http://guides.rubyonrails.org/v3.2.21/action_controller_overview.html#default_url_options

【讨论】:

    【解决方案5】:

    Rails.application.routes.default_url_options[:host]= 'localhost:3000'

    在developemnt.rb/test.rb中,可以更简洁如下:

    Rails.application.configure do
      # ... other config ...
    
      routes.default_url_options[:host] = 'localhost:3000'
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      相关资源
      最近更新 更多