Peter
Peter

Reputation: 132327

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?

Upvotes: 16

Views: 9361

Answers (3)

Santi Bivacqua
Santi Bivacqua

Reputation: 101

You should use extending

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

For more info: ActiveRecord::QueryMethods

Upvotes: 6

Tanzeeb Khalili
Tanzeeb Khalili

Reputation: 7344

Create a self.summed_values method directly in the transaction model.

Upvotes: 18

emrass
emrass

Reputation: 6444

Is there any specific reason why you want to create this method as extension to ActiveRecord::Relation? I would propose a class method like so:

class Transaction ...
  def self.summed_values(transactions=nil)
    if transactions.nil?
      all.sum(...)...
    else
      where(id => transactions).sum(...)...
    end
  end
end

This also has the advantage that it is only available for transactions.

Upvotes: 1

Related Questions