user2490003
user2490003

Reputation: 11890

Correct way to unset dependent associations before destroying a record?

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 Players 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 -

  1. Define a before_destroy hook on Team that clears Player#team_id on it's various players

  2. 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

Answers (1)

max
max

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

Related Questions