In DB there ara many accounts, every account has lots of transactions with price attribute. It's needed to count account balance by summarize all transaction prices.
class AccountsController < ApplicationController
def index
@accounts = Account.all
end
end
Account model:
class Account < ActiveRecord::Base
has_many :transactions, dependent: :destroy
includes :transactions
def balance
transactions.sum(:price) || 0
end
def balance_ruby_sum
sum = 0
transactions.each { |t| sum+= t.price }
sum
end
end
Transaction model:
class Transaction < ActiveRecord::Base
belongs_to :account
end
account index.html.erb:
<table>
<th>name</th>
<th>balance</th>
<% @accounts.each do |acc| %>
<td><%= acc.name %></td>
<td><%= acc.balance %></td>
<% end %>
</table>
In index view I have account's name and its balance.
It's needed to fire N+1 queries to DB to do this and I want to avoid N+1 problem.
I tried to use balance_ruby_sum
action instead of balance
action (only 2 queries are needed), but it's not a good solution (performance issue).
I don't want to retrieve all full transaction, only their sum of prices. Is it possible to count balance by sum prices using SQL and do only 2 queries?
I found an article there in 4 item described how to use a query object. But I don't understand how to create a one in my case.