当模型同时具有一个和多个相同模型时的 ActiveRecord 关系
我的数据类似于这样:
class Team < ActiveRecord::Base
has_many :persons
has_one :leader
end
class Person < ActiveRecord::Base
belongs_to :team
end
一个人只属于一个团队,但在众多团队成员中只有 1 位领导者。
第一个问题:我应该在团队模型中使用belongs_to而不是has_one吗?
第二:团队是由许多人和最初已知的领导者创建的。这应该怎么做呢?
目前我正在我的控制器中做这样的事情:
@team = Team.new
for (each new person as p)
new_person = @team.persons.build
new_person.name = p.name
if p.is_marked_as_leader
@team.leader = new_person
end
end
@team.save
这是一个问题,当我列出@team.persons时,@team.leader有第一个id,我假设因为@team.save首先保存领导者关联。我需要它们按照提供的顺序排列。
谢谢!
My data resembles this:
class Team < ActiveRecord::Base
has_many :persons
has_one :leader
end
class Person < ActiveRecord::Base
belongs_to :team
end
Person only belongs to one Team, but of the many team members there is only 1 leader.
First question: should I use belongs_to instead of has_one in the Team model?
Second: Team is created with many Persons and the leader known initially. How should this be done?
Currently I am doing something like this in my controller:
@team = Team.new
for (each new person as p)
new_person = @team.persons.build
new_person.name = p.name
if p.is_marked_as_leader
@team.leader = new_person
end
end
@team.save
This is a problem, when I list @team.persons, @team.leader has the first id, I assume because @team.save saves the leader association first. I need them to be in the order they are provided.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会投票给领导者“has_one”,因为你这个人可以存在于团队之外,而她作为团队领导的角色。
这是聚合与组合讨论。
有时这是有争议的,但在这种情况下,我会说团队与领导者的关系显然是组成的。
I would vote for 'has_one' for the leader, because you the person can exist outside the team and her role as team lead.
It is the aggregation vs composition discussion.
Sometimes this is open to debate, but in this case I would say the team - leader relationship is clearly composition.