[英]How can I access polymorphic_path inside a model in Rails 4?
Pretty simple, I want to use the polymorphic_path
method inside a Rails 4 model.非常简单,我想在 Rails 4 模型中使用
polymorphic_path
方法。 Yes I know it's poor separation of concerns.是的,我知道它的关注点分离很差。 And I know about
Rails.application.routes.url_helpers
, but polymorphic_path
isn't in there.我知道
Rails.application.routes.url_helpers
,但polymorphic_path
不在那里。
Try including also PolymorphicRoutes
:尝试也包括
PolymorphicRoutes
:
include ActionDispatch::Routing::PolymorphicRoutes
include Rails.application.routes.url_helpers
def link
polymorphic_path(self)
end
I know the OP specified Rails 4 but in case someone else ends up here looking for the answer using Rails 5 like I did, here are two ways to access polymorphic_path
in a model in Rails 5 :我知道 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
Or, if you want to avoid including all methods, just add a private method that wraps the call and you're good to go!或者,如果您想避免包含所有方法,只需添加一个封装调用的私有方法即可!
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
Notice that the class doesn't need to inherit from ApplicationRecord, both methods work with POROs (Plain-Old Ruby Object).请注意,该类不需要从 ApplicationRecord 继承,这两种方法都适用于 PORO(Plain-Old Ruby 对象)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.