Ruby on rails RubyonRails4.0-加载和使用模块

Ruby on rails RubyonRails4.0-加载和使用模块,ruby-on-rails,Ruby On Rails,阅读全文,我对在Rails 4中加载和包含模块的正确方法感到困惑。 我想在我的几个应用程序模型中包括此模块: module SimpleSearch def self.search(filter) if filter.present? where('name like ?', "%#{filter}%") else where('TRUE') end end end 文件路径为lib/simple\u search.rb 由于Michae

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

module SimpleSearch
  def self.search(filter)
    if filter.present?
      where('name like ?', "%#{filter}%")
    else
      where('TRUE')
    end
  end
end
文件路径为
lib/simple\u search.rb
由于Michael的建议,我更新了
config/application.rb
以帮助加载模块(问题3已解决):

在模型中,我包括:

class BusinessRule < ActiveRecord::Base
extend SimpleSearch
class-BusinessRule
并在执行时获取一个新错误:

undefined method `search' for #<ActiveRecord::Relation::ActiveRecord_Relation_BusinessRule:0x00000003670770>
未定义的方法“搜索”#
  • extend
    与此相关吗

  • 我是否使用了正确的语法、模块和文件名

  • 是否需要进行配置以确保加载了库/模块,还是按惯例

  • 谢谢你的帮助

    致以最良好的祝愿


    Fred

    尝试将其添加到
    config/application.rb

    config.autoload_paths += %W(#{config.root}/lib)
    
    摘自这里:

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

    然后,模块定义不应参考
    self

    以下是工作正常的代码更新:

    module SimpleSearch
      def search(filter)
        if filter.present?
          where('name like ?', "%#{filter}%")
        else
          where('TRUE')
        end
      end
    end
    
    欢迎大家发表意见,

    致以最良好的祝愿

    弗雷德

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