Как добавить дополнительный атрибут в модель, чтобы убрать расчет из поля зрения? - PullRequest
0 голосов
/ 25 февраля 2012

Для следующего кода RubyOnRails есть способ переместить вычисление "прибыли" из представления в модель ... так что, возможно, есть атрибут с именами total_income и total_expense * * 1005

Модель - транзакция.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

<code><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>

Ответы [ 2 ]

2 голосов
/ 25 февраля 2012

Для самых основных изменений вы можете просто добавить методы класса в транзакцию

class Transaction < ActiveRecord::Base
  attr_accessible :name, :amount, :category
  scope :incomes,  :conditions => { :category => 'Income'  }
  scope :expenses, :conditions => { :category => 'Expense' }

  def self.income_total
    incomes.sum :amount
  end

  def self.expenses_total
    expenses.sum :amount
  end

end

class TransactionsController < ApplicationController

  def index
    @incomes  = Transaction.incomes
    @expenses = Transaction.expenses
    @income_total = Transaction.income_total
    @expenses_total = Transaction.expenses_total
    @transaction = Transaction.new
  end
1 голос
/ 25 февраля 2012

В наши дни я предпочитаю обернуть эти несколько взаимозависимых переменных экземпляра в новый класс презентаторов, что-то вроде этого (не проверено) :

<code>class TransactionPresenter

  attr_reader :income_total, :expenses_total

  def initialize
    @incomes = Transaction.incomes
    @expenses = Transaction.expenses
  end

  def each_income(&block)
    @incomes.each(&block)
  end

  def each_expense(&block)
    @incomes.each(&block)
  end

  def income_total
    @income_total ||= number_to_currency(@incomes.sum(&:amount))
  end

  def expenses_total
    @expenses_total ||= number_to_currency(@expenses.sum(&:amount))
  end

  def name_and_amount(income_or_expense)
    "#{income_or_expense.name} - #{number_to_currency((income.amount.nil? ? 0 : income.amount))}"
  end

  def profit
    number_to_currency(income_total - expenses_total)
  end

end

# controller

def index
  @presenter = TransactionPresenter.new
end

# view

<pre>
<strong>Income</strong>
  <% @presenter.each_income do |income| %>
    <%= @presenter.name_and_amount %>
  <% end %>
  <strong>Subtotal:</strong> <%= @presenter.income_total %>

<strong>Expenses</strong>
  <% @presenter.each_expense do |expense| %>
    <%= @presenter.name_and_amount %>
  <% end %>
  <strong>Subtotal:</strong> <%= @presenter.expenses_total %>

<strong>Profit: <%= @presenter.profit %></strong>
...