在 Rails 下,has_one
真的是“最多只有一个”。将所有三个has_one
装饰器都放在User
. 如果你想确保他们只有一个,你可以添加一个验证,例如:
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
由于您有能力更改数据库中的 users 表,我想我会将club_id
, team_id
, player_id
in放入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
我什至很想重命名User
为Manager
, 或has_one :manager, :class_name => "User"
在Club
,Team
和Player
模型中拥有 , 但你的电话。