0

**更新**这一切似乎都与自定义验证器有关:如果我删除它,它会按预期工作。见最后代码**

我有一个模型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
4

2 回答 2

0

它可能取决于您的 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.save
于 2013-03-01T17:17:41.683 回答
0

所以看起来罪魁祸首在这里

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-02T17:23:23.503 回答