0

我正在尝试根据下图计算和排序表中的余额列;

图片

为此,我用于 @mexpenses = @mexpenses.sort { |e| e.balance }排序,因为它会导致不想要的结果,所以我在下面的代码中注释掉了。

我想达到上图中最右边的BALANCE列所示的结果。

表中从日期列到借方列的所有内容都按需要显示,只有余额列导致问题。

我想以适当的余额在语句顶部获取最新记录。

注意:数据库中没有余额列。

meexpenses_controller.rb

def index
  @mexpenses = Mexpense.order('date DESC')
  balance = 763.87
  @mexpenses.each do |e|
    balance += e.credit.to_f - e.debit.to_f
    e.balance = balance
  end

  # @mexpenses = @mexpenses.sort { |e| e.balance }  

  respond_to do |format|
    format.html
    format.xls 
  end
end

费用.rb

class Mexpense < ActiveRecord::Base

    validates :particulars, presence: true
    validates :date, presence: true
    
    attr_accessor :balance

    after_initialize :init

    def init
        self.balance = 0
    end
end

index.html.erb

<div class="row">

    <div class="col-md-8 col-md-offset-2">

      <div class="table-responsive myTable">

        <table class="table listing text-center">
          <tr class="tr-head">
            <td>Date</td>
            <td>Particulars</td>
            <td>Credit</td>
            <td>Debit</td>
            <td>Balance</td>
          </tr>

          <tr>
            <td></td>
          </tr>


          <% @mexpenses.each do |mexpense| %>

          <tr class="tr-<%= cycle('odd', 'even') %>">

            <td class="col-1"><%= mexpense.date.strftime('%d/%m/%Y') %></td>

            <td class="col-1" style="width: 50%;"><%= link_to mexpense, mexpense %></td>

            <td class="col-1 neg" style="width: 10%;"><%= number_with_precision(mexpense.credit, :delimiter => ",", :precision => 2) %></td>

            <td class="col-1 pos" style="width: 10%;"><%= number_with_precision(mexpense.debit, :delimiter => ",", :precision => 2) %></td>


            <td><%= number_with_precision(mexpense.balance, :delimiter => ",", :precision => 2) %></td>

          </tr>

          <% end %>

        </table>
      </div>
    </div>

  </div>

20210213052730_create_mexpenses.rb

class CreateMexpenses < ActiveRecord::Migration
  def change
    create_table :mexpenses do |t|
      t.date :date
      t.string :particulars
      t.decimal :debit
      t.decimal :credit

      t.timestamps null: false
    end
  end
end

任何建议都非常受欢迎。

先感谢您。

4

1 回答 1

0
  1. 我强烈建议将该balance列存储在数据库中。每次debitcredit更改时,balance列都会更新。

  2. 把钱存起来integer!!!!这避免了浮点舍入错误。

安慰:

rails g migration add_balance_to_mexpenses balance:integer

移民:

add_column :mexpenses, :balance, :integer, default: 0, null: false

mexpence.rb - 每当 `mexpence 更改时更新余额列

after_save do
  update :balance, credit - debit
end

现在,您可以轻松地按余额排序,这是数据库中的一个单独字段。就像是:

@mexpenses = Mexpense.order(date: :desc, balance: :desc)
于 2021-02-16T13:02:34.023 回答