Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 823
originalproject Avatar asked Nov 18 '14 20:11

originalproject


2 Answers

Try including also PolymorphicRoutes:

include ActionDispatch::Routing::PolymorphicRoutes
include Rails.application.routes.url_helpers

def link
  polymorphic_path(self)
end
like image 185
markets Avatar answered Oct 18 '22 05:10

markets


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).

like image 1
Goulven Avatar answered Oct 18 '22 05:10

Goulven