Question

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.

Pas de solution correcte

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top