【发布时间】: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.
- 我是否正确定义了模型关联?
- 在创建或编辑团队时,如何将球员或队长分配给团队?
任何帮助将不胜感激。
【问题讨论】:
标签: ruby-on-rails activerecord