这个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/
发布于 2012-04-12 08:39:03
我认为您需要为has_many定义设置:autosave => true选项。
如上所述,这里:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many
如果为true,则在保存父对象时,始终保存关联的对象或销毁标记为销毁的对象。如果为false,则从不保存或销毁关联的对象。默认情况下,仅保存作为新记录的关联对象。
https://stackoverflow.com/questions/8100763
复制相似问题