Add values from a column with Ruby

Asked

Viewed 947 times

1

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

I’m trying the following on Activerecord

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

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

Thanks for your attention!

2 answers

1

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

in his model:

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

on your controller:

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

in your view on app/Payments/index.html.erb:

<%= @sum_of_payments %>

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

0

The class that represents your model may contain a class method that calculates the sum of all debt values. I’m guessing there’s a table dividas in your database, which contains a column valor.

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 that will return the total of all debts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.