Help! Sum with mysql database criterion

Add DB column conditioned to a criterion, for example: A =1 B=1 A=1 C=4 A=2 SUMIF: A=4 B=1 C=4

Using CONTROLLER,

> class PaymentsController < ApplicationController
>   def index
>     @sum_of_payments = Payment.total
>   end
> end

MODEL

class Payment
  def self.total
    self.sum(:value)
  end
end

VIEW

<%= @sum_of_payments %>

If you want the sum of payment values for each user:

class Payment
  def self.total
    sum(:value).group(:user_id)
  end
end
1 Like