1

我有几个跨越多个表的聚合函数。目前,我将它们作为其中一个类中的类方法,但我真的很想将它们放在一个中央模块或类中,因为它们并不是真正特定于该类,我们现在将它们放在多个类中。我想把它们放在一个模块中,但不能扩展 ActiveRecord::Base。像这样的东西,但这不起作用,因为没有用于 global_aggregations 的表:

class GlobalAggregation < ActiveRecord::Base

  def self.say_hello
    puts "say hello"
    sql="select * from locations" # this would join a bunch of tables
    items=self.find_by_sql(sql)
  end
end

有没有办法设置一个派生自 ActiveRecord::Base 的类,只是为了在没有其他功能或其他想法的情况下获取查询接口如何处理这个问题?

4

1 回答 1

0

您不想创建一个继承自 的类ActiveRecord::Base,因为从该类继承的类根据定义应该是 AR 模型。您也不想打补丁ActiveRecord::Base,因为这不是Base所有模型都应该可用的功能。您可以Base从另一个模块内部调用方法:

module GlobalAggregator

  def say_hello
    puts "say hello"
    sql = "select * from locations" # this would join a bunch of tables
    items = ActiveRecord::Base.find_by_sql(sql)
  end

end
于 2013-06-08T10:01:57.447 回答