【问题标题】:belongs_to has_one structurebelongs_to has_one 结构
【发布时间】:2010-08-24 12:21:00
【问题描述】:

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

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

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

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

【问题讨论】:

  • 不清楚用户代表什么。如果俱乐部有球队,而球队有球员,那么 / 是 / 用户是什么?它有什么,有什么?
  • 对此感到抱歉。我编辑了问题以澄清用户表。
  • 啊,我明白了。用户本质上是俱乐部、球队或球员之一的“经理”。你有能力改变数据库中的用户表吗?
  • 是的,如果需要,我可以更改用户表。我正在使用 restful-authentication 从该表登录用户。
  • 好的。我在下面编辑了我的答案。

标签: ruby-on-rails activerecord belongs-to has-one


【解决方案1】:

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

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_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 =&gt; "User",但您的电话。

【讨论】:

  • 我想过在user表中添加三个id。我们将如何识别已登录的“实体”。对于每个用户,只有一个 club_id 或 team_id 或 player_id。我将检查所有三个以查看用户是否属于俱乐部、球队或球员。从User 模型到俱乐部/团队/球员有更好的方法吗?
  • 我怀疑你可以用abstract_class? 或多态关联做一些聪明的事情;但我倾向于在用户中有一个方法,比如def managed ; club || team || player ; end
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多