before_save 中的 mark_for_destruction

Posted

技术标签:

【中文标题】before_save 中的 mark_for_destruction【英文标题】:mark_for_destruction in before_save 【发布时间】:2011-11-11 22:30:32 【问题描述】:

这个before_save-callback有什么问题?

class Order < ActiveRecord::Base

    has_many :line_items, :dependent => :destroy, :inverse_of => :order
    accepts_nested_attributes_for :line_items  
    attr_accessible :line_items_attributes


    before_save :mark_line_items_for_removal

    def mark_line_items_for_removal
      line_items.each do |line_item|
         line_item.mark_for_destruction if line_item.quantity.to_f <= 0
      end
    end
end

line_items 之一被标记为销毁时,不会保存line_item。 但是,父 Order 对象确实被保存了。 返回 true 并没有什么不同...

关于mark_for_destruction:http://apidock.com/rails/v3.1.0/ActiveRecord/AutosaveAssociation/mark_for_destruction 为什么用 ":allow_destroy => true" 代替?看这里: http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/

【问题讨论】:

if line_item.quantity.to_f &lt;= 0 可能有问题?例如,您确定它并不总是错误的吗? 不,我检查了“puts line_item.marked_for_destruction?”在那条线之后。它给出了预期的结果。但是当其中一个被标记时,他们都没有被保存...... 你找到答案了吗?我注意到将子项目标记为销毁将导致不保存标记的机器人和下一个项目(IE:-1,1,2 - 只会保存 2) 【参考方案1】:

我相信您需要为您的 has_many 定义设置 :autosave => true 选项。

如前所述,这里:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

“如果为true,则在保存父对象时始终保存关联对象,如果标记为销毁,则销毁它们。如果为false,则从不保存或销毁关联对象。默认情况下,仅保存新记录的关联对象。”

【讨论】:

以上是关于before_save 中的 mark_for_destruction的主要内容,如果未能解决你的问题,请参考以下文章

Ruby on Rails:before_save 字段为小写

Rails:before_save 变量内容

带有 MD5 摘要的 Rails 模型 before_save

before_save,剥离一个字符串

Rails :before_save 大写私有方法

检查模型是不是在 before_save 事件中被修改或创建