当模型同时具有一个和多个相同模型时的 ActiveRecord 关系

发布于 2024-09-10 19:17:54 字数 673 浏览 7 评论 0原文

我的数据类似于这样:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九公里浅绿 2024-09-17 19:17:54

我会投票给领导者“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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文