Nov*_*paX 6 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)
当其中之一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/
我相信您需要为 has_many 定义设置 :autosave => true 选项。
如前所述,这里:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many
“如果为 true,则在保存父对象时,始终保存关联对象或销毁它们(如果标记为销毁)。如果为 false,则从不保存或销毁关联对象。默认情况下,仅保存新记录的关联对象。”
| 归档时间: |
|
| 查看次数: |
5245 次 |
| 最近记录: |