简体   繁体   中英

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. Something like this but this doesn't work as there isn't a table for 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?

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. You don't want to monkey patch ActiveRecord::Base either because this isn't Base functionality that should be available to all models. You can just call Base methods from inside another module:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM