首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >before_save中的mark_for_destruction

before_save中的mark_for_destruction
EN

Stack Overflow用户
提问于 2011-11-12 06:30:33
回答 1查看 5.3K关注 0票数 6

这个before_save-callback有什么问题?

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

EN

回答 1

Stack Overflow用户

发布于 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,则从不保存或销毁关联的对象。默认情况下,仅保存作为新记录的关联对象。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8100763

复制
相关文章

相似问题

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