我的数据类似于:
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 之一
谢谢!