【问题标题】:Uninitialized content when trying to include ActionController::UrlWriter in model尝试在模型中包含 ActionController::UrlWriter 时未初始化的内容
【发布时间】:2011-03-02 00:12:41
【问题描述】:

我正在使用 Rails 3 beta 4 并尝试在我的模型中包含 ActionController::UrlWriter,据我所知,这是正确的方法,但我得到“未初始化的常量 ActionController::UrlWriter” .

知道为什么会这样吗?它在轨道 3 中移动了吗?

【问题讨论】:

  • 在你的模型中包含控制器的部分通常是错误的
  • 我需要能够在模型相关的、绝对不是控制器相关的操作中生成 named_routes。它还应该去哪里?库?

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

首先我同意zed。这不应该在模型中完成。您的模型应该不知道任何 http url。

我在一个resque工作中做同样的事情。这就是我所做的:

include ActionDispatch::Routing::UrlFor
include ActionController::PolymorphicRoutes
include Rails.application.routes.url_helpers
default_url_options[:host] = 'example.com'

然后你可以调用任何常用的 url 生成器。

url_for(object)
page_url(object)

它将在定义为default_url_options[:host]的主机上创建链接

【讨论】:

  • 对不起,我没明白。那么 midas06 应该把代码放在哪里呢?为什么还要包含 ActionController::PolymorphicRoutes?不在 ActionController 中?
【解决方案2】:

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?的回答都不错

或看

http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html

http://siddharth-ravichandran.com/2010/11/26/including-url-helpers-in-models/

基本上,您可以在模型中执行以下操作:

def url
  Rails.application.routes.url_helpers.download_attachment_path(self)
end

不过,这是否是正确的层值得考虑。在我的情况下,它是用于文件附件的,我想做 attachment.url 而不是大量写出帮助程序。

【讨论】:

    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 2011-05-26
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多