简体   繁体   English

Rails-在保存之前迭代has_many关联的嵌套属性

[英]Rails - Iterating a Nested Attributes of has_many association before saving

I have a model and a has_many association. 我有一个模型和has_many关联。

Say, 说,

class Invoice < ActiveRecord::Base
  has_many :lines, class_name: 'InvoiceLine', inverse_of: :invoice, dependent: :destroy
  accepts_nested_attributes_for :lines, reject_if: :invalid_line, allow_destroy: true
end

Is it possible for me to iterate through the lines before it is saved (especially during an update), either in InvoicesController or in Invoice model? 在InvoicesController或Invoice模型中,在保存之前(尤其是在更新期间),我是否可以遍历各行?

When I iterate on the existing record during an update, I get old lines, not the updated lines from the view. 在更新期间对现有记录进行迭代时,我得到的是旧行,而不是视图中的更新行。

Currently I am doing the following in the controller. 目前,我正在控制器中执行以下操作。 I am not quite happy with this. 我对此不太满意。

total = params["invoice"]["lines_attributes"].
          map{|k,v| [v["amount"], v["_destroy"]]}.
          select{|x| x[1] == "false"}.
          map{|x| x[0].to_f}.
          inject {|total, amount| total + amount}

You can use assign_attributes and marked_for_destruction? 您可以使用assign_attributesmarked_for_destruction吗? as: 如:

@invoice.assign_attributes(params[:invoice]) @ invoice.assign_attributes(params [:invoice])
total = @invoice.lines.select(&:marked_for_destruction?).map(&:amount).sum 总计= @ invoice.lines.select(&:marked_for_destruction?)。map(&:amount).sum
@invoice.save #save all on db @ invoice.save#全部保存在数据库中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails accepts_nested_attributes_for通过以下方式不保存has_many上的关联 - Rails accepts_nested_attributes_for not saving association on has_many through 通过关联未创建具有has_many的Rails嵌套属性 - Rails Nested Attributes with has_many through association not creating Rails 3 - has_many关联未保存(TypeError) - Rails 3 - has_many association not saving (TypeError) 用于 has_many 关联的 Rails 嵌套属性“没有将符号隐式转换为整数” - Rails nested attributes "no implicit conversion of Symbol into Integer" for has_many association Rails 5通过与n + 1关联来注册嵌套属性has_many - Rails 5 Register nested attributes has_many through association with n+1 Rails bug:accepts_nested_attributes_for没有更新我的has_many关联 - Rails bug: accepts_nested_attributes_for is not updating my has_many association 如何将强参数中的嵌套属性与 has_many 关联合并 - How to merge nested attributes in strong params with has_many association has_many accepts_nested_attributes_for关联问题 - has_many accepts_nested_attributes_for association question 嵌套属性与 has_many 通过关联创建对象两次 - Nested attributes with has_many through association creating object twice 具有has_many的模型中属性的总和:通过关联在Rails 5中不起作用 - Sum of attributes in model with has_many :through association not working in Rails 5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM