Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define method on activerecord relation

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 Transactions, is there any way to tell rails to only define this method for ActiveRecord::Relations that consist of Transactions?

like image 948
Peter Avatar asked Jul 21 '12 07:07

Peter


People also ask

What are ActiveRecord methods?

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.

What is ActiveRecord relation?

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.

What's the purpose of ActiveRecord?

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.

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


1 Answers

You should use extending

Transaction.all.extending do
  def summed_values
    sum(:what_you_want)
  end
end

For more info: ActiveRecord::QueryMethods

like image 199
Santi Bivacqua Avatar answered Nov 04 '22 17:11

Santi Bivacqua