I want to define a custom method on an activerecord relation, eg:
Transaction.all.summed_values
A simple example would be where summed_values
should evaluate sum(:value)
on the relation.
Where should I define the method summed_values
? Looks like it should be on ActiveRecord::Relation
. If it should be directly there, which file should I put it in?
Also, if this new method only has meaning for Transaction
s, is there any way to tell rails to only define this method for ActiveRecord::Relation
s that consist of Transaction
s?
The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save.
Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet). Once you run that query by calling to_a , each , first etc. on that Relation a single instance or an array of ActiveRecord::Base instances will be returned.
Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
You should use extending
Transaction.all.extending do
def summed_values
sum(:what_you_want)
end
end
For more info: ActiveRecord::QueryMethods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With