I have the models Player
, Team
and PlayerTeam
; PlayerTeam
is the middle table that forms the many to many relationship between Player
and Team
.
player.rb:
class Player < ApplicationRecord
has_many :player_teams
has_many :teams , through: :player_teams
before_save do
self.numero_goals = 0
self.reputation = 0
self.plays_win = 0
self.plays_lose = 0
end
end
team.rb:
class Team < ApplicationRecord
has_many :player_teams, dependent: :destroy
has_many :players, through: :player_teams
has_many :team_battles, dependent: :destroy
has_many :battles, through: :team_battles
end
player_team.rb:
class PlayerTeam < ApplicationRecord
belongs_to :player
belongs_to :team
end
The routes I currently have it like this:
resources :players do
resources :player_teams
end
resources :teams do
resources :player_teams
end
I want to know how I can organize it in the best way so that, once a Player
is created, it can choose a Team
or create it, to automatically save it in the PlayerTeam
table.