Rails在關聯關系中,han_one和has_many都有一個:dependent選項,告訴ActiveRecord在刪除父記錄時該如何處理子記錄,它有五個屬性(AWDWR):
  1. :dependent => :destroy(或true) --- 刪除父記錄的同時刪除子表中的記錄
  2. :dependent => :nullify  --- 刪除父記錄之后保留子記錄,同時將子記錄的外鍵值設置為null
  3. :dependent => :false(或nil) --- 刪除父記錄時不改變子記錄。
但是在使用的過程中,設置為: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方法 。