has_many 关联与 has_many 中的 own_to 引用发生混乱

发布于 2024-09-11 01:13:20 字数 615 浏览 5 评论 0原文

我的数据类似于这样:

class Team < ActiveRecord::Base
  has_many :persons
 belongs_to :leader, :class_name => "Person"
end

class Person < ActiveRecord::Base
  belongs_to :team
end

我像这样创建团队:

  @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在人员之前保存了领导者关联。我需要它们按照提供的顺序排列,其中 :leader own_to 引用我的 has_many :persons 中的 ID 之一,

谢谢!

My data resembles this:

class Team < ActiveRecord::Base
  has_many :persons
 belongs_to :leader, :class_name => "Person"
end

class Person < ActiveRecord::Base
  belongs_to :team
end

I create the Team like this:

  @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

When I list @team.persons, @team.leader has the first id, I guess because @team.save is saving the leader association before persons. I need them to be in the order they are provided, where the :leader belongs_to references one of the ID's within my has_many :persons

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

没有伤那来痛 2024-09-18 01:13:20

您不应该依赖 ID 的任何特定顺序,可能会发生很多事情。您可以分配另一个数据库列来以某种方式表示顺序。

如果您想这样做,只需在创建人员时保存人员,因为那时将分配 ID:

new_person = @team.persons.build
new_person.name = p.name
new_person.save

如果您担心数据库一致性,请包装 for 循环和 < code>@team.save 在事务中,因此如果其中一个失败,它们都会回滚。

You shouldn't rely on ID's to be in any particular order, there are a lot of things that can happen. You could assign another DB column to represent the ordering somehow.

If you want to do it though, just save the people as you create them, since that is when the ID's will get assigned:

new_person = @team.persons.build
new_person.name = p.name
new_person.save

If you're worried about database consistency, wrap the for loop and the @team.save in a transaction, so they all get rolled back if one fails.

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