Good I will consider that you already have Rails properly installed and configured on your machine.
It is unclear whether your method is really a method of Model or a action
(a method of Controller), but I think it’s a action
, because you are calling a method that is probably a method of a Model. Good considering these correct assumptions we can perform the following steps to make it work.
We created our Controller
and our action
(we will use generator
to expedite the procedure)
Rails g controller operations sum
That will beget our controller
in app/controllers/operacoes_controler.rb
class OperacoesController < ApplicationController
def somar
end
end
And it will generate our view on app/views/operacoes/somar.html.erb
<h1>Operacoes#somar</h1>
<p>Find me in app/views/operacoes/somar.html.erb</p>
Okay now we’re almost there, I don’t know your model
Registro
, nor what you wish to add, I will consider that he has a field saldo
and you want to add up the value of each saldo
in all the records.
*** For test I managed the model
Registro
, but you probably won’t need to take this step, I’ll put it here to demonstrate how I performed the procedure.
Rails g model record balance:integer
*** In the console I created 3 records to test the logic, which you probably won’t need to do either.
2.3.1 :001 > Registro.create(saldo: 1)
=> #<Registro id: 1, saldo: 1, created_at: "2016-07-14 23:56:46", updated_at: "2016-07-14 23:56:46">
2.3.1 :002 > Registro.create(saldo: 2)
=> #<Registro id: 2, saldo: 2, created_at: "2016-07-14 23:56:50", updated_at: "2016-07-14 23:56:50">
2.3.1 :003 > Registro.create(saldo: 3)
=> #<Registro id: 3, saldo: 3, created_at: "2016-07-14 23:56:53", updated_at: "2016-07-14 23:56:53">
Resolution of the question
Place the value assignment on action
of OperacoesController
class OperacoesController < ApplicationController
def somar
@valor = Registro.sum('saldo')
end
end
And put the @valor
amid tags erb
<%= @valor =%>
in your View (app/views/operacoes/somar.html.erb
). Example:
<h1>A soma dos saldos de todos os registros é <%= @valor %> </h1>
Access: http://localhost:3000/operacoes/somar
And the result will be something like this:
EDIT:
Case wanted to re-use this method in several Views
one can use a Helper
as Rafael quoted. That is, remove from the OperacoesController
and add to ApplicationHelper
, ex:
# /app/helpers/application_helper.rb
module ApplicationHelper
def saldo_total
Registro.sum('saldo')
end
end
in your View would look like this
#app/views/operacoes/index.html.erb
<h1>A soma dos saldos de todos os registros é <%= saldo_total %> </h1>
Sorry, but there are numerous ways to get this result, can you be more specific editing and reformulating your question so we can answer in a specific way? Adding your main difficulty in the issue also helps. Hugs.
– Rafael Berro