我正在尝试根据下图计算和排序表中的余额列;
为此,我用于 @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
任何建议都非常受欢迎。
先感谢您。