我有一个具有以下特征的应用程序
There are Clubs Each Club has Teams Each Team has Players
我有一个用户表。用户表基本上包含俱乐部经理,球队经理和登录系统的球员的用户名和密码。
我应该如何构建模型和表格?
我计划为俱乐部,球队和球员创建牌桌。但我不确定show是否构建了它们与users表之间的关系。
我可以在每个模型中创建user_id
,但关系将是Club belongs_to User
,这似乎不正确。此外,我最终会得到一个具有以下
has_one :club
has_one :team
has_one :player
哪个不对。用户在任何给定时间只能拥有其中一个。
有没有更好的方法来构建它?
答案 0 :(得分:1)
在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
放在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
,但是你的电话。