Can I set up Cascade deleting in Rails?

后端 未结 5 730
情深已故
情深已故 2020-12-23 11:02

I know this is probably on the Internet somewhere but I can\'t find the answer here on Stackoverflow so I thought I may boost up the knowledge base here a little.

I\

5条回答
  •  爱一瞬间的悲伤
    2020-12-23 11:42

    Contrary to the provided answer I highly suggest also doing this on a database level. In case you have different processes or a multi threaded environment it could happen that records are not properly deleted. Furthermore the database foreign key makes things way faster when deleting lots of data.

    Like in the suggested answer do this:

    has_many :memberships, dependent: :delete_all
    

    However also make sure to setup a foreign_key in a migration. That way the database takes care of deleting the records automatically for you.

    To nullify the values when a membership is deleted, assuming you have a user model:

    add_foreign_key :users, :memberships, on_delete: :nullify
    

    You can also delete all the models whenever a membership is deleted

    add_foreign_key :users, :memberships, on_delete: :cascade
    

提交回复
热议问题