ActiveRecord级联删除
Rails在关联关系中,han_one和has_many都有一个:dependent选项,告诉ActiveRecord在删除父记录时该如何处理子记录,它有五个属性(AWDWR):
[color=red]:dependent => :destroy(或true) --- 删除父记录的同时删除子表中的记录
:dependent => :nullify --- 删除父记录之后保留子记录,同时将子记录的外键值设置为null
:dependent => :false(或nil) --- 删除父记录时不改变子记录。[/color]
但是在使用的过程中,设置为:destroy或:nullify,都没有达到效果,由于使用的是rails2.2.2,看了一下has_many的源码:
# [:dependent]
# If set to <tt>:destroy</tt> all the associated objects are destroyed
# alongside this object by calling their +destroy+ method. If set to <tt>:delete_all</tt> all associated
# objects are deleted *without* calling their +destroy+ method. If set to <tt>:nullify</tt> all associated
# objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. *Warning:* This option is ignored when also using
# the <tt>:through</tt> option.
发现选项已经变成了:
:destroy
:delete_all
:nullify
但发现也没有达到要求。
最后发现controller代码中调用的是ActiveRecord的delete方法,换成destroy方法后,发现能够正常地级联删除子记录。
对于ActiveRecord,delete方法不能级联删除子记录,而要使用destroy方法 。
Rails在关联关系中,han_one和has_many都有一个:dependent选项,告诉ActiveRecord在删除父记录时该如何处理子记录,它有五个属性(AWDWR):
[color=red]:dependent => :destroy(或true) --- 删除父记录的同时删除子表中的记录
:dependent => :nullify --- 删除父记录之后保留子记录,同时将子记录的外键值设置为null
:dependent => :false(或nil) --- 删除父记录时不改变子记录。[/color]
但是在使用的过程中,设置为:destroy或:nullify,都没有达到效果,由于使用的是rails2.2.2,看了一下has_many的源码:
# [:dependent]
# If set to <tt>:destroy</tt> all the associated objects are destroyed
# alongside this object by calling their +destroy+ method. If set to <tt>:delete_all</tt> all associated
# objects are deleted *without* calling their +destroy+ method. If set to <tt>:nullify</tt> all associated
# objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. *Warning:* This option is ignored when also using
# the <tt>:through</tt> option.
发现选项已经变成了:
:destroy
:delete_all
:nullify
但发现也没有达到要求。
最后发现controller代码中调用的是ActiveRecord的delete方法,换成destroy方法后,发现能够正常地级联删除子记录。
对于ActiveRecord,delete方法不能级联删除子记录,而要使用destroy方法 。