【发布时间】:2011-07-19 02:55:00
【问题描述】:
我正在尝试找到为团队/成员/个人定义模型的最佳方式,其中一个人可以是多个团队的成员,一个团队可以有多个成员。与“成员”关系一起的是该人为团队担任的职位。一支球队也应该只有一名主教练和一名助理教练。一个人可以是多个团队的主教练/助理教练。
以下是我目前的(徒劳的)尝试:
class Team < ActiveRecord::Base
has_many :members
has_many :people, :through => :members
belongs_to :head_coach :class => 'Person'
belongs_to :assistant_coach :class => 'Person'
end
class Person < ActiveRecord::Base
has_many :teams
has_many :teams, :through => :members
end
class Member < ActiveRecord::Base
belongs_to :team
belongs_to :person
# has a "position" which is a string
end
这种方法给我带来了两个问题:
-
团队的 belongs_to :head_coach 和 :assistant_coach 不起作用。也许它应该是一个has_one,但是我不确定将belongs_to放在Person中是否有意义(我想要一个FK in Team to Person)。下面的示例显示我的设置方式与 ActiveRecord 不符:
irb(main):006:0> t = Team.find(1) => #<Team id: 1, name: "Champs", created_at: "2011-07-18 01:50:56", updated_at: "2011-07-19 01:47:26", head_coach: nil> irb(main):007:0> t.head_coach => nil irb(main):008:0> t.head_coach = Person.find(1) => #<Person id: 1, name: "Chris", created_at: "2011-07-18 01:52:34", updated_at: "2011-07-18 01:52:34"> irb(main):009:0> t.save => true irb(main):010:0> t.head_coach => #<Person id: 1, name: "Chris", created_at: "2011-07-18 01:52:34", updated_at: "2011-07-18 01:52:34"> irb(main):011:0> Team.find(1).head_coach => nil -
has_many :through 似乎有效,但我还没有找到一种列出团队中每个人的职位的好方法。这是我目前在视图中的尝试:
<% @team.people.each do |person| %> <%= person.name +" "+ @team.members.find_by_person_id(person).position %>
是否有更好的方法来表示这些关系?
感谢您的帮助!
-克里斯
【问题讨论】:
标签: ruby-on-rails-3 activerecord