before_save中的mark_for_destruction

时间:2011-11-11 22:30:33

标签: ruby-on-rails ruby before-save

这个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对象确实已保存。 回归真实并没有什么不同......

关于mark_for_destruction:http://apidock.com/rails/v3.1.0/ActiveRecord/AutosaveAssociation/mark_for_destruction 为什么而不是“:allow_destroy =&gt; true”?看这里: http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/

1 个答案:

答案 0 :(得分:3)

我相信你需要设置:autosave =&gt;你的has_many定义的真正选项。

如上所述,这里:

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

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