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

There are Clubs
Each Club has Teams
Each Team has Players

我有一个用户表。用户表基本上包含俱乐部经理,团队经理和播放器登录系统的用户名和密码。

我应该如何构建模型和表格?

我计划为俱乐部,团队和球员创建桌子。但是我不确定要构建他们与用户表之间的关系。

我可以创建 user_id 在每个模型中,但是关系将是 Club belongs_to User 这似乎不正确。此外,我最终将获得具有以下内容的用户模型

has_one :club
has_one :team
has_one :player

这是不对的。用户在任何给定时间只有一个。

有更好的方法来构建这个问题吗?

有帮助吗?

解决方案

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

由于您有能力更改数据库中的用户表,因此我想我会放 club_id, team_id, player_idusers, ,并保持以下内容:

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, TeamPlayer 模型,但是您的电话。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top