belongs_to has_one结构

时间:2010-08-24 12:21:00

标签: ruby-on-rails activerecord 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

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

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

1 个答案:

答案 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_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,或has_one :manager, :class_name => "User"ClubTeam模型中有Player ,但是你的电话。