【问题标题】:Rails 3 Model associations with has_many, belongs_to and :throughRails 3 模型与 has_many、belongs_to 和 :through 的关联
【发布时间】:2010-11-12 07:07:16
【问题描述】:

我正在尝试为我正在进行的一个小项目组合几个模型关联。我是 Rails 新手,所以这对我来说有点困惑。

我的用例非常简单。我有一个体育联赛有很多 部门。每个部门 有许多 团队。每个团队 有一个 队长有很多 玩家

现在,玩家和队长都由职业用户代表。唯一区别他们的是他们的角色。我正在使用 CanCan 来管理角色。

现在这里是我的模型以及我如何定义关联:

class Division < ActiveRecord::Base
  belongs_to :league
  has_many :teams
end

class League < ActiveRecord::Base
  has_many :divisions
end

class Team < ActiveRecord::Base
  belongs_to :division
  accepts_nested_attributes_for :division

  has_one :captain, :class_name => "User"
  accepts_nested_attributes_for :captain

  has_many :rosters
  has_many :players, :through => :rosters, :source => :user
  accepts_nested_attributes_for :players

  validates_presence_of :name
  validates_uniqueness_of :name
end

class User < ActiveRecord::Base
  has_many :authentications
  has_many :rosters
  has_many :teams, :through => :rosters
  belongs_to :team
end

And here is my generated Schema file.

  1. 我是否正确定义了模型关联?
  2. 在创建或编辑团队时,如何将球员或队长分配给团队?

任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:
    1. 我觉得这个定义没问题。 (当然)还有其他方法可以做到这一点,但这个似乎还可以。

    2. 这取决于您的 UI。船长应该足够简单 - 执行 collection_select 并将其分配给 captain 属性。

    玩家有点棘手。通常的方法是(就像你一样)使用collection_select和一个html数组name(例如team[player_id][]),在你的情况下,我想你每个球队都有一定数量的球员,所以你只需显示它很多次(如果没有,您可以使用 javascript 为用户克隆它)。

    【讨论】:

    • 我有兴趣了解定义这些模型和关联的不同方式。因为老实说,所有这些 belongs_to 和 has_many 的东西真的让我很困惑。
    • 例如,您可以不将队长定义为 has_one,而是将其作为名册模型的属性。但是在这种情况下使用 has_one 似乎很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2022-07-08
    相关资源
    最近更新 更多