如何在 Rails 4 的 lib/module 中使用 polymorphic_path

mb2*_*b21 5 ruby-on-rails ruby-on-rails-4

我想打电话给polymorphic_path位于辅助模块中lib/my_module.rb

我从这个答案中尝试了以下内容,它适用于模型,但不适用于我的模块:

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

  def link(model)
    polymorphic_path(model)
  end
end
Run Code Online (Sandbox Code Playgroud)

我得到:

undefined method `polymorphic_path' for MyModule:Module
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我通过config.autoload_paths += %W(#{config.root}/lib)in加载我的模块config/application.rb

mb2*_*b21 -1

结果你必须创建一个类才能正确包含 ruby​​ 中的内容,例如:

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

  def link(model)
    polymorphic_path(model)
  end
end
Run Code Online (Sandbox Code Playgroud)