Pretty simple, I want to use the polymorphic_path
method inside a Rails 4 model. 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.
Try including also 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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With