Ruby on Rails 4.0 – 加载和使用模块

阅读,我对在Rails 4中加载和包含模块的正确方法感到困惑。我想将此模块包含在我的应用程序的几个模型中:

module SimpleSearch def self.search(filter) if filter.present? where('name like ?', "%#{filter}%") else where('TRUE') end end end 

文件路径是lib/simple_search.rb感谢Michael的建议,我更新了config/application.rb来帮助加载模块(问题3已经解决):

 config.autoload_paths += %W(#{config.root}/lib) 

在模型中,我包括:

 class BusinessRule < ActiveRecord::Base extend SimpleSearch 

并在执行时获得新错误:

 undefined method `search' for # 
  1. 这里extend相关吗?

  2. 我是否使用正确的语法,模块和文件名?

  3. 是否有配置以确保加载lib /模块或是否为常规?

谢谢你的帮助,

最好的祝福,

弗雷德

尝试将其添加到config/application.rb的类定义中

 config.autoload_paths += %W(#{config.root}/lib) 

取自这里: Rails 4模块的未初始化常量

据我所知, search函数是一个类函数,因此使用extend包含它是相关的。

然后,模块定义不应该引用self

以下代码更新工作正常:

 module SimpleSearch def search(filter) if filter.present? where('name like ?', "%#{filter}%") else where('TRUE') end end end 

您的意见是受欢迎的,

最好的祝福,

弗雷德