**更新**这一切似乎都与自定义验证器有关:如果我删除它,它会按预期工作。见最后代码**
我有一个模型budget
有很多multi_year_impacts
在控制台中,如果我运行:
b = Budget.find(4)
b.multi_year_impacts.size #=> 2
b.update_attributes({multi_year_impacts_attributes: {id: 20, _destroy: true} } ) #=> true
b.multi_year_impacts.size #=> 1 (so far so good)
b.reload
b.multi_year_impacts.size #=> 2 What???
如果在b.reload
我这样做之前b.save
(无论如何都不应该需要),那也是一样的。
知道为什么我的孩子记录没有被销毁吗?
一些额外的信息,以防万一:
导轨 3.2.12
在budget.rb
attr_accessible :multi_year_impacts_attributes
has_many :multi_year_impacts, as: :impactable, :dependent => :destroy
accepts_nested_attributes_for :multi_year_impacts, :allow_destroy => true
validates_with MultiYearImpactValidator # problem seems to com from here
在multi_year_impact.rb
belongs_to :impactable, polymorphic: true
在multi_year_impact_validator.rb
class MultiYearImpactValidator < ActiveModel::Validator
def validate(record)
return false unless record.amount_before && record.amount_after && record.savings
lines = record.multi_year_impacts.delete_if{|x| x.marked_for_destruction?}
%w[amount_before amount_after savings].each do |val|
if lines.inject(0){|s,e| s + e.send(val).to_f} != record.send(val)
record.errors.add(val.to_sym, " please check \"Repartition per year\" below: the sum of all lines must be equal of total amounts")
end
end
end
end