How to use polymorphic_path in lib/module in Rails

2019-06-27 12:12发布

问题:

I want to call polymorphic_path in a helper module located at lib/my_module.rb.

I tried the following from this answer, which works in a model, but not in my module:

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

  def link(model)
    polymorphic_path(model)
  end
end

I get:

undefined method `polymorphic_path' for MyModule:Module

Btw, I load my module through config.autoload_paths += %W(#{config.root}/lib) in config/application.rb.

回答1:

Turns out you have to create a class to properly include stuff in ruby, for example:

class MyClass
  include ActionDispatch::Routing::UrlFor
  include Rails.application.routes.url_helpers

  def link(model)
    polymorphic_path(model)
  end
end