我有一个模型和一个has_many关联。
说,
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
在InvoicesController或Invoice模型中,我可以在保存之前迭代这些行(特别是在更新期间)吗?
当我在更新期间迭代现有记录时,我会看到旧行,而不是视图中的更新行。
目前我在控制器中执行以下操作。我对此并不满意。
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}
答案 0 :(得分:0)
您可以使用assign_attributes和marked_for_destruction?作为:
@ invoice.assign_attributes(PARAMS [:发票])
total = @ invoice.lines.select(&amp;:marked_for_destruction?)。map(&amp;:amount).sum
@ invoice.save #save all on db