對於以下RubyOnRails代碼,是否有移動的「利潤」計算出來的查看,並納入模型的方式..所以也許有一個名爲total_income和total_expense屬性?如何在模型中添加額外屬性以將計算移出視圖?
型號 - transaction.rb
class Transaction < ActiveRecord::Base
attr_accessible :name, :amount, :category
scope :incomes, :conditions => { :category => 'Income' }
scope :expenses, :conditions => { :category => 'Expense' }
end
控制器 - transactions_controller.rb
class TransactionsController < ApplicationController
def index
@incomes = Transaction.incomes
@expenses = Transaction.expenses
@transaction = Transaction.new
end
視圖 - 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>
與您的問題無關:小心,交易是許多編程環境中的保留字,可能會導致問題。爲了避免問題,我總是調整一下名稱的習慣。 – DGM 2012-02-25 01:35:59
@DGM感謝您指出了這一點。一些RoR保留字(我發現它包括'transaction')列在[RoR舊wiki](http://oldwiki.rubyonrails.org/rails/pages/ReservedWords)上。 – Turgs 2012-02-25 06:14:30