【问题标题】:Disordering of a has_many association with belongs_to reference into the has_many将 has_many 关联与 belongs_to 引用打乱到 has_many 中
【发布时间】:2010-07-21 05:31:54
【问题描述】:

我的数据类似于:

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 belongs_to 引用了我的 has_many :persons 中的 ID 之一

谢谢!

【问题讨论】:

    标签: ruby-on-rails has-many belongs-to


    【解决方案1】:

    您不应该依赖 ID 的任何特定顺序,有很多事情可能发生。您可以指定另一个 DB 列以某种方式表示排序。

    如果您想这样做,只需在创建人员时保存他们,因为这是分配 ID 的时间:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多