默认的URL选项和Rails 3

17

ActionController::Base#default_url_options 未被废弃 - Mohamad
5个回答

26

要为当前请求设置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

很遗憾,当其声明为受保护时会抛出异常,这是必须的(否则它将作为一个动作暴露)。因此它无法工作。 - gucki
4
这在我的实际项目中很有效,我不知道为什么你认为它会显示为一个操作,只需从路由中删除默认的/:controller/(:action)。这个方法必须是公开的。 - Łukasz Śliwa
它也适用于邮件发送器,只需在ActionMailer :: Base的子类中定义方法即可 :) - gucki
你如何根据模型属性设置选项?例如,将 :profile 设置为 comment.user.city_name,这样我们就可以得到 /newyork/comments/123 - QWJ QWJ
comments_path(:profile => comment.user.city_name, :id => comment.id)评论路径(:个人资料=>评论.用户.城市名称,:id=>评论.id) - Łukasz Śliwa
显示剩余2条评论

24

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

Rails.application.routes.default_url_options[:foo]= 'bar' 
你可以将这行代码放在 routes.rb 或者初始化文件中,看你喜欢哪一个。如果根据环境值的变化,你甚至可以将其放在环境配置中。

1
但是我该如何使其依赖于当前请求,例如访问实例变量? - gucki
2
看起来这就是Rails 3.2的结局了。 - aceofspades
14
这是一个愚蠢的问题:你把这行代码放在哪里?是在routes.rb文件中吗?还是在初始化代码中? - Dan Tao
如果您必须在配置级别设置此项,那么如何传递动态的 account_id?例如 scope '/:account_id' - 您如何能够在配置级别动态设置 account_id - Mohamad
这个在Rails 5.1.4中不再适用于页面渲染,只适用于rails控制台。 - lulalala
显示剩余3条评论

4

1
我认为指南已经过时了,而不是api文档。这种方法在Rails 3.2中不再起作用。 - jpgeek

0

对于特定的 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


0

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

在 development.rb / test.rb 中,可以更简洁地写成以下形式:

Rails.application.configure do
  # ... other config ...

  routes.default_url_options[:host] = 'localhost:3000'
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接