如何在Rails 4中访问模型中的polymorphic_path?

时间:2014-11-18 20:17:33

标签: ruby-on-rails ruby-on-rails-4 routing

非常简单,我想在Rails 4模型中使用polymorphic_path方法。是的,我知道关注点很差。我知道Rails.application.routes.url_helpers,但polymorphic_path不在那里。

2 个答案:

答案 0 :(得分:7)

尝试同时包含PolymorphicRoutes

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

def link
  polymorphic_path(self)
end

答案 1 :(得分:0)

我知道OP指定了Rails 4,但是如果其他人像我一样最终在这里使用Rails 5寻找答案,则有两种方法访问Rails 5中的模型中的polymorphic_path < / strong>:

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(普通旧式Ruby对象)一起使用。