Define a method regarding activerecord

I want to define a custom method for an activerecord relationship, for example:

Transaction.all.summed_values

A simple example: where summed_valuesshould evaluate sum(:value)in relation.

Where should I define a method summed_values? Looks like he should be on ActiveRecord::Relation. If it should be directly there, in which file should I put it?

Also, if this new method makes sense only for Transactions, is there a way to tell the rails to only define this method for ActiveRecord::Relationwhich consists of Transactions?

+5
source share
3 answers

Create a method self.summed_valuesdirectly in the transaction model.

+7
source

- , ActiveRecord:: Relation? :

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

, .

+1

You must use the extension

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

For more information: ActiveRecord :: QueryMethods

+1
source

All Articles