Rails: delete cascade vs dependent destroy

北战南征 提交于 2019-12-29 04:29:06

问题


Assuming I have two tables: users and orders. A user has many orders, so naturally there is a foreign key user_id in my orders table.

What is the best practice in rails (in terms of speed, style and referential integrity) to ensure that if a user is deleted, all dependent orders are also deleted? I am considering the following options:

Case 1. Using :dependent => :destroy in the user model

Case 2. Defining the table orders in postgres and writing

user_id integer REFERENCES users(id) ON DELETE CASCADE

Is there any reason why I should use Case 1? It seems that Case 2 is doing all I want it to do? Is there are difference in terms of execution speed?


回答1:


It really depends on the behavior you want. In case 1, destroy will be called on each associated order, and therefor so will the ActiveRecord callbacks. In case 2, these callbacks are not triggered, but it will be way faster and guarantees referential integrity.

In an application's infancy, I'd recommend going with :dependent => :destroy because it lets you develop in a way that is independent of the database. Once you start to scale, you should start doing it in the database for performance/integrity reasons.




回答2:


has_many :orders, dependent: :destroy

  • Safest option for automatically maintaining data integrity.
  • You have polymorphic associations, and do not want to use triggers.


add_foreign_key :orders, :users, on_delete: :cascade (in database migration)

  • You are not using any polymorphic associations or you want to use triggers for each polymorphic association.


has_many :orders, dependent: :delete_all

  • Only use when the has_many is a leaf node on your association tree (i.e. the child does not have another has_many association with foreign key references)



回答3:


I would use option 1. While it may work, I can see a number of issues with option 2:

  1. ActiveRecord will be unaware that these records were deleted, which could lead to unstable behavior
  2. it would be unclear to anyone reading the code that deleting a user means that all their orders will also be deleted
  3. any destroy handlers on Order would not fire

Certainly I would expect option 2 to be faster, but it's up to you if the trade-offs are worth it. Is deletion of a user a common operation in your application?

Another option would be to use :dependent => :delete_all. This would be faster than :dependent => :destroy and avoid drawbacks 1 and 2 above. See here for more details.



来源:https://stackoverflow.com/questions/12556614/rails-delete-cascade-vs-dependent-destroy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!