简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM