将模块混合到轨道上的红宝石模型中

Vic*_*box 1 activerecord ruby-on-rails

我希望将几个模型共享的功能抽象到一个模块中.

我有这个型号:

class Report < ActiveRecord::Base
  include AppModel
  has_and_belongs_to_many :tag
  belongs_to :city
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

(另外,如何让我的代码在stackoverflow上跨越多行?它不会保留我的换行符.)

然后我有一个模块(在app/models/app_model.rb中):

module AppModel 
  def self.list
    find(:all, :order => 'name asc').map { |item| [item.name, item.id] }
   end
end
Run Code Online (Sandbox Code Playgroud)

但如果我这样做Report.list不起作用.我怀疑在我做的模块中是否存在问题def function或者def self.function

如此反复,我的问题是,如何让我访问的功能,例如Report.list或者Report.find_tagged是一个模块中定义.

Ana*_*oly 5

包括混合实例方法,而不是类级别.使用extend方法或orverride include.

PS使用代码格式化SO使用{}