belongs_to has_one结构

我有一个具有以下特点的应用程序

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 

哪个不对。 用户在任何给定时间只能拥有其中一个。

有没有更好的方法来构建它?

在Rails下, has_one实际上“最多只有一个”。 在User拥有所有三个has_one装饰器是完全有效的。 如果您想确保它们只有一个,您可以添加validation,例如:

 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_idteam_idplayer_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 ,或者在ClubTeamPlayer模型中拥有has_one :manager, :class_name => "User" ,但是你的电话。