[英]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_attributes和marked_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.