For the following RubyOnRails code, is there a way to move the "profit" calculation out of the View and into the Model.. so there's maybe an attribute called total_income and total_expense?
Model - transaction.rb
class Transaction < ActiveRecord::Base
attr_accessible :name, :amount, :category
scope :incomes, :conditions => { :category => 'Income' }
scope :expenses, :conditions => { :category => 'Expense' }
end
Controller - transactions_controller.rb
class TransactionsController < ApplicationController
def index
@incomes = Transaction.incomes
@expenses = Transaction.expenses
@transaction = Transaction.new
end
View - index.html.erb
<pre>
<strong>Income</strong>
<% @incomes.each do |income| %>
<%= income.name %> - <%= number_to_currency((income.amount.nil? ? 0 : income.amount)) %>
<% end %>
<strong>Subtotal:</strong> <%= number_to_currency(@income_total = @incomes.sum(:amount)) %>
<strong>Expenses</strong>
<% @expenses.each do |expense| %>
<%= expense.name %> - <%= number_to_currency((expense.amount.nil? ? 0 : expense.amount)) %>
<% end %>
<strong>Subtotal:</strong> <%= number_to_currency(@expenses_total = @expenses.sum(:amount)) %>
<strong>Profit: <%= number_to_currency(@income_total - @expenses_total) %></strong>
</pre>