加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – before_save中的mark_for_destruction

发布时间:2020-12-17 02:16:26 所属栏目:百科 来源:网络整理
导读:这个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_ite
这个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 => true”?看这里:
http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/

解决方法

我相信你需要设置:autosave => has_many定义的true选项.

如上所述,这里:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读