Home > Software engineering >  How to destroy a dependent if it is aliased?
How to destroy a dependent if it is aliased?

Time:06-09

class Team < ApplicationRecord

end
class Game < ApplicationRecord
  belongs_to :winner, class_name: 'Team'
  belongs_to :loser, class_name: 'Team'
end

Thanks in advance. Is it possible to write a dependence for destroy a belonged Game instance when a Team instance is destroyed? I didn't find anything on it, all things, I tried, like

class Team < ApplicationRecord
  has_many :games, inverse_of: :winner, dependent: :destroy
...

didn't work.

CodePudding user response:

You need to add foreign keys

class Team < ApplicationRecord
  has_many :winner_games, foreign_key: :winner_id, class_name: 'Game', dependent: :destroy
  has_many :loser_games, foreign_key: :loser_id, class_name: 'Game', dependent: :destroy
end
  • Related