dependent destroy not working

后端 未结 2 2011
礼貌的吻别
礼貌的吻别 2021-02-13 21:18

I\'m trying to use dependent: :destroy without success.

Lets put a simple example. I create a simple application with the following:

rails g model parent         


        
相关标签:
2条回答
  • 2021-02-13 21:33

    4.2.2.4 :dependent

    If you set the :dependent option to:

    • :destroy, when the object is destroyed, #destroy will be called on its associated objects.
    • :delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their #destroy method.

    As per your settings, you have to do p.destroy.

    The :dependent option can have different values which specify how the deletion is done. For more information, see the documentation for this option on the different specific association types. When no option is given, the behaviour is to do nothing with the associated records when destroying a record.

    For has_many, destroy and destroy_all will always call the destroy method of the record(s) being removed so that callbacks are run. However delete and delete_all will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is :nullify (set the foreign keys to nil), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).

    0 讨论(0)
  • 2021-02-13 21:54

    Calling the delete method on an ActiveRecord derived object will issue a direct DELETE statement do the database, skipping any ActiveRecord callbacks and configurations such as dependent: destroy.

    I believe you want the destroy method.

    You could also set up a foreign key in the database and set it to cascade on delete, it might make sense, depending on your needs.

    0 讨论(0)
提交回复
热议问题