** update **这一切似乎都与自定义验证器有关:如果我删除它,它就会像预期的那样工作。见末尾的代码**
我有一个模型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 (无论如何也不应该需要),它也是一样的。
知道为什么我的孩子记录没有被销毁吗?
一些补充资料,以防万一:
Rails 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发布于 2013-03-02 17:23:23
所以看起来凶手就在这里
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将此更改为稍微复杂一些的
total = 0
lines.each do |l|
total += l.send(val).to_f unless l.marked_for_destruction?
end
if total != record.send(val)
record.errors[:amount_before] << " please check \"Repartition per year\" below: the sum of all lines must be equal of total amounts"
end解决了问题。
发布于 2013-03-01 17:17:41
但是,它可能取决于rails版本,将代码与当前的文档进行比较。
现在,当您将_destroy键添加到属性哈希(其值为true )时,您将销毁关联的模型: member.avatar_attributes ={ :id => '2',:_destroy => '1‘} member.avatar.marked_for_destruction?# => true member.save member.reload.avatar # => nil 注意,在保存父模型之前,不会销毁该模型。
你可以试着:
b.multi_year_impacts_attributes = {id: 20, _destroy: true}
b.savehttps://stackoverflow.com/questions/15162530
复制相似问题