如何在rails one_to_many关联中执行计算?

问题描述 投票:0回答:1

  • 项目与财务有一对多关联
  • 财务与付款里程碑具有一对多关联
  • 每个付款里程碑都有一个字段amount_invoice和amount_realized。现在我想计算所有payment_milestone的amount_invoice和amount_realized的差值,然后求和并在project#index中显示它们。我试过了但是我出错了这是我尝试的代码-

    <% @projects.each do |project| %>
        <% @financials = Financial.where(project_id: project.id) %>
        <%  @Payment_milestones = PaymentMilestone.where(financial_id: @financials.ids) %>
    
        <%  outstanding_payment = 0 %>
        <%  @Payment_milestones.each{|s| outstanding_payment += s.amount_invoiced-s.amount_realized if s.amount_invoiced > s.amount_realized } %>
        <% @outstanding_payment = outstanding_payment %>
        <td><%= @outstanding_payment %></td>
    <% end %>
    
    ruby-on-rails ruby-on-rails-5
    1个回答
    0
    投票

    由于s.amount_invoiced为零,您得到了错误。>

    是否有可能将amount_invoiced和amount_realized的默认值设置为0?(由于[C​​0]不能与nil一起使用,而不能用于整数或浮点数)

    OR

    您可以将代码更改为:<

    © www.soinside.com 2019 - 2024. All rights reserved.