下軌,has_one
真是「至多有一個」。在User
中擁有全部三個has_one
修飾器是完全有效的。如果你想確保他們只有剛好一個,你可以添加一個驗證,例如:
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
因爲你必須改變在數據庫中的用戶表的能力,我想我會把club_id
,team_id
, player_id
在users
,並有以下幾點:
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
我甚至被引誘在Club
,Team
和Player
月更名爲User
Manager
,或有has_one :manager, :class_name => "User"
dels,但你的電話。
目前還不清楚用戶代表什麼。如果俱樂部有球隊,而球隊有球員,那麼用戶是什麼?它有什麼,它有什麼? – Chowlett 2010-08-24 12:26:39
對不起。我編輯了這個問題來澄清用戶表。 – Addy 2010-08-24 12:38:30
啊,我明白了。用戶本質上是俱樂部,團隊或玩家之一的「經理」。你有能力改變數據庫中的用戶表嗎? – Chowlett 2010-08-24 12:58:33