下轨,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