深层嵌套表单属性的总和

时间:2016-03-20 14:08:29

标签: ruby-on-rails cocoon-gem

rails 4 + cocoon

一点背景:

orders has_many order_products order_products has_many product_sizes

在after_save通话中,我想获得所有产品的总数量。我在total_qty模型中有一个名为order_product的数据库列。所以在这张照片中,总数将是37。

Screen shot

订单

= f.simple_fields_for :order_products do |order_product|
    = render 'order_product_fields', :f => order_product
      = link_to_add_association 'Add Product', f, :order_products

order_product_fields

= f.simple_fields_for :product_sizes do |product_size|
      = render 'product_size_fields', :f => product_size
        = link_to_add_association 'Add Size', f, :product_sizes

product_size_fields

<div class="row nested-fields">
 = f.input :size_name, :collection => Order::SIZES, label: false, include_blank: false
 = f.input :qty, label: false, class: "<%= product_sizes.index %>"
 = link_to_remove_association f, class: 'btn btn-danger' do
  .glyphicon.glyphicon-remove
</div>

1 个答案:

答案 0 :(得分:0)

我最终深挖并在脑中找到答案。

product_size.rb

  def size_qty
    qty
  end

order_product.rb

  def total_size_qty
    product_sizes.map do |ps| ps.size_qty end
  end

order.rb

def total_order_product_qty
  order_products.map do |os| os.total_size_qty end
end
相关问题