Adding values from a column with Ruby

1

Hello, I'm starting out with Ruby On Rails, and I'm making an application that manages expenses. Well what I need to do add up all the expenses of the "value" column and show in the view.

I'm trying the following in ActiveRecord

def total
    divida.sum("valor * ")
end

Would that be the right way? How do I show it in the view?

Thank you for your attention!

    
asked by anonymous 01.10.2014 / 05:02

2 answers

1

You can do as the one quoted in the other answer, but never call a method of a model in a view, since model does not communicate with view, and this is one of the fundamentals of MVC. You can call this method in your control, refer to a variable and use it in your view

in your model:

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

in your controller:

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

in your view in app / payments / index.html.erb:

<%= @sum_of_payments %>

ps: avoid writing code in Portuguese, and worse, mixing English with Portuguese.

    
21.11.2014 / 23:04
0

The class representing your model can contain a class method that calculates the sum of all debt values. I'm assuming there is a dividas table in your database, which contains a valor column.

class Divida < ActiveRecord::Base
  def self.total
    self.sum(:valor)
  end
end

Then in your view (for example, the file app/views/divida/index.html.erb ), you can call Divida.total which will return the total of all debts.

    
01.10.2014 / 22:54