Reputation: 11890
Say I have 2 ActiveRecord models - Team
, and Player
, with a simple parent/child relationship
class Team < ApplicationRecord
has_many :players
end
class Player < ApplicationRecord
belongs_to :team
end
Rails provides options like dependent: :destroy
to specify what happens to the child associations when a parent is destroyed.
But what if I don't necessarily want destroy the Player
s when I destroy
a Team
? Instead, I'd like to unset the team_id
field on each Player
and then safely destroy
the Team
.
Is there a best practice approach to do that?
My thought was -
Define a before_destroy
hook on Team
that clears Player#team_id
on it's various players
Define a after_rollback
hook on Team
that handles the case when something had to be rolled back. This would re-add the team_id
to all the Player
models, basically reversing what we just did
Is #2 necessary? Or does a rollback handle reversing what I already did? And overall is this the best way to approach this?
Would be curious to hear if anyone has a simpler approach.
Thanks!
Upvotes: 0
Views: 32
Reputation: 101811
class Team < ApplicationRecord
has_many :players, dependent: :nullify
end
class Player < ApplicationRecord
belongs_to :team, optional: true
end
See options for the dependent option.
Upvotes: 2