Is it safe to have circular dependent: :destroy options in ActiveRecord models?

class Student < ActiveRecord::Base
  has_one :user, dependent: :destroy
end
class User < ActiveRecord::Base
  belongs_to :student, dependent: :destroy
end

If I delete a user, it should delete the associated student. And vice-versa.

没有正确的解决方案

其他提示

Yes. AR will just issue delete queries for each entity within a single transaction. So, let's say a user has 2 students (a and b). If you delete student a, AR will delete student a, causing a delete of user, causing a delete of student b, causing a final duplicate delete of user. The duplicate delete (aside from a small performance hit), will not cause any sort of error. The reverse, deleting the user will also work fine.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top