[英]How can I access polymorphic_path inside a model in Rails 4?
非常简单,我想在 Rails 4 模型中使用polymorphic_path
方法。 是的,我知道它的关注点分离很差。 我知道Rails.application.routes.url_helpers
,但polymorphic_path
不在那里。
尝试也包括PolymorphicRoutes
:
include ActionDispatch::Routing::PolymorphicRoutes
include Rails.application.routes.url_helpers
def link
polymorphic_path(self)
end
我知道 OP 指定了 Rails 4,但如果其他人最终像我一样使用 Rails 5 寻找答案,这里有两种方法可以访问 Rails 5 模型中的polymorphic_path
:
class Something
# The following line is enough, no need for ActionDispatch::Routing::PolymorphicRoutes in Rails 5
include Rails.application.routes.url_helpers
end
或者,如果您想避免包含所有方法,只需添加一个封装调用的私有方法即可!
class Something
def do_stuff
polymorphic_path(a_resource)
end
private
def polymorphic_path(resource)
Rails.application.routes.url_helpers.polymorphic_path(resource)
end
end
请注意,该类不需要从 ApplicationRecord 继承,这两种方法都适用于 PORO(Plain-Old Ruby 对象)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.