How can I define custom getter functions for ActiveRecord objects in Ruby that will perform operations on an array of ActiveRecord objects?
For example, I would like to return weighted averages to an array of objects. Therefore, if I have Loan objects (1,2,3) with the sums of the fields (100, 200, 300) and default_rate (.1, .2, .3), then with the usual functions ActiveRecord Loan.find (1). amount should return 100, Loan.find (2) .default_rate should return .2.
But if I had Loan.find (2,3) .default_rate, I would like it to return the default weighted average of bids, which is .26. I know that I can do this with SQL select statements, but how can I "overload" the getter ActiveRecord to allow the function to be defined when I call getter in an array of Loan objects, and not in a single Loan object?
The loan table shows the quantity, quantity, and default value.
class Loan < ActiveRecord::Base module Collection def default_rate sum(:default_rate * :amount) / sum(:amount) end end end class LoanGroup has_many :loans, :extend => Loan::Collection end #Then I try obj = LoanGroup.where('id < 10')
This gives me an error that has_many is undefined in LoanGroup
source share