【发布时间】:2012-02-25 00:40:32
【问题描述】:
对于以下 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>
【问题讨论】:
-
与您的问题无关:注意,Transaction 是许多编程环境中的保留字,可能会导致问题。我养成了总是稍微调整名称以避免问题的习惯。
-
@DGM 感谢您指出这一点。 RoR old wiki 上列出了一些 RoR 保留字(我发现确实包括“交易”)。
标签: ruby-on-rails refactoring rails-activerecord