Rails在關聯關系中,han_one和has_many都有一個:dependent選項,告訴ActiveRecord在刪除父記錄時該如何處理子記錄,它有五個屬性(AWDWR):
發現選項已經變成了:
最后發現controller代碼中調用的是ActiveRecord的delete方法,換成destroy方法后,發現能夠正常地級聯刪除子記錄。
對于ActiveRecord,delete方法不能級聯刪除子記錄,而要使用destroy方法 。
- :dependent => :destroy(或true) --- 刪除父記錄的同時刪除子表中的記錄
- :dependent => :nullify --- 刪除父記錄之后保留子記錄,同時將子記錄的外鍵值設置為null
- :dependent => :false(或nil) --- 刪除父記錄時不改變子記錄。
# [: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.
# 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方法 。