简体   繁体   English

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

[英]How to use polymorphic_path in lib/module in Rails 4

I want to call polymorphic_path in a helper module located at lib/my_module.rb . 我想在位于lib/my_module.rb的辅助模块中调用polymorphic_path

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 . 顺便说一下,我通过config/application.rb config.autoload_paths += %W(#{config.root}/lib)加载我的模块。

Turns out you have to create a class to properly include stuff in ruby, for example: 事实证明你必须创建一个类来正确地包含ruby中的东西,例如:

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

  def link(model)
    polymorphic_path(model)
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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