我希望将几个模型共享的功能抽象为一个模块。
我有这个型号:
class Report < ActiveRecord::Base
include AppModel
has_and_belongs_to_many :tag
belongs_to :city
belongs_to :user
end
(还有,我如何让我的代码在stackoverflow上跨多行?它不会保留我的换行符。(
然后我有一个模块(在app/models/app_model.rb中(:
module AppModel
def self.list
find(:all, :order => 'name asc').map { |item| [item.name, item.id] }
end
end
但如果我做Report.list
,它就不起作用。我怀疑如果在模块中我执行def function
或def self.function
,会有问题吗?
因此,我的问题是,如何使模块中定义的函数(如Report.list
或Report.find_tagged
(可访问。
include混合实例方法,而不是类级别。使用extend方法或覆盖include。
第页。S.要在SO上使用代码格式,请使用{}