belongs_to struttura has_one
-
30-09-2019 - |
Domanda
Ho un'applicazione che ha le seguenti caratteristiche
There are Clubs Each Club has Teams Each Team has Players
Ho una tabella utenti. La tabella utente contiene fondamentalmente il nome utente e la password per il manager del club, team manager e il giocatore per accedere al sistema.
Come devo strutturare i modelli e le tabelle?
ho intenzione di creare tabelle per Club, squadra e giocatori. Ma non sono sicuro spettacolo per strutturare il rapporto tra loro e il tavolo degli utenti.
ho potuto creare user_id
in ogni modello, ma il rapporto sarebbe Club belongs_to User
che non sembra giusto. Inoltre vorrei finire con un modello User che ha la seguente
has_one :club
has_one :team
has_one :player
Il che non è giusto. Un utente avrà solo uno di loro in un dato momento.
C'è un modo migliore per strutturare questo?
Soluzione
Under Rails, has_one
è realmente "ha al massimo un". E 'perfettamente valido per avere tutti e tre i decoratori has_one
in User
. Se si vuole garantire hanno solo appunto uno, si potrebbe aggiungere una convalida, per esempio:
class User < ActiveRecord::Base
has_one :club
has_one :team
has_one :player
validate :has_only_one
private
def has_only_one
if [club, team, player].compact.length != 1
errors.add_to_base("Must have precisely one of club, team or player")
end
end
end
Dal momento che si ha la possibilità di modificare la tabella utenti nel database, penso che avrei messo club_id
, team_id
, player_id
in users
, e hanno la seguente:
class Club < ActiveRecord::Base
has_one :user
has_many :teams
has_many :players, :through => :teams
end
class Team < ActiveRecord::Base
has_one :user
belongs_to :club
has_many :players
end
class Player < ActiveRecord::Base
has_one :user
belongs_to :team
has_one :club, :through => :team
end
class User < ActiveRecord::Base
belongs_to :club
belongs_to :team
belongs_to :player
validate :belongs_to_only_one
def belongs_to_only_one
if [club, team, player].compact.length != 1
errors.add_to_base("Must belong to precisely one of club, team or player")
end
end
end
Mi piacerebbe anche essere tentato di rinominare User
come Manager
, o hanno has_one :manager, :class_name => "User"
nei modelli Club
, Team
e Player
, ma la chiamata.