[英]singleton object to run query with in a Ruby module or class in a Rails app
I have several aggregation function that span multiple tables. 我有几个跨多个表的聚合函数。 Currently, I have them as class methods in one of the classes but would really like to put them in a central module or class since they are not really specific to the class and we now have them in multiple classes.
目前,我将它们作为一个类中的类方法使用,但由于它们并不是特定于该类的,因此我们真的希望将它们放在一个中央模块或类中,并且现在将它们包含在多个类中。 I was thinking of just putting them in a module but can't extend ActiveRecord::Base.
我当时只是想将它们放在模块中,但不能扩展ActiveRecord :: Base。 Something like this but this doesn't work as there isn't a table for global_aggregations:
像这样的事情,但是由于没有用于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
Is there a way to setup a class that dervives from ActiveRecord::Base just to get at query interface without other functionality or other idea how to handle this? 有没有一种方法可以设置一个从ActiveRecord :: Base派生的类,而只是在没有其他功能或如何解决此问题的其他想法的情况下进入查询接口?
You don't want to make a class that inherits from ActiveRecord::Base
, as classes that inherit from that should by definition be AR models. 您不想创建一个从
ActiveRecord::Base
继承的类,因为从该类继承的类按照定义应该是AR模型。 You don't want to monkey patch ActiveRecord::Base
either because this isn't Base
functionality that should be available to all models. 您不希望猴子修补
ActiveRecord::Base
,因为这不是应用于所有模型的Base
功能。 You can just call Base
methods from inside another module: 您可以从另一个模块内部调用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.