首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails:为什么这个marked_for_destruction没有被销毁?

Rails:为什么这个marked_for_destruction没有被销毁?
EN

Stack Overflow用户
提问于 2013-03-01 16:40:04
回答 2查看 1.6K关注 0票数 0

** update **这一切似乎都与自定义验证器有关:如果我删除它,它就会像预期的那样工作。见末尾的代码**

我有一个模型budget,它有很多multi_year_impacts

在控制台中,如果我运行:

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
belongs_to :impactable, polymorphic: true

multi_year_impact_validator.rb

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-02 17:23:23

所以看起来凶手就在这里

代码语言:javascript
复制
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

将此更改为稍微复杂一些的

代码语言:javascript
复制
  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

解决了问题。

票数 0
EN

Stack Overflow用户

发布于 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 注意,在保存父模型之前,不会销毁该模型。

你可以试着:

代码语言:javascript
复制
b.multi_year_impacts_attributes =  {id: 20, _destroy: true}
b.save
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15162530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档