2010-07-20 66 views
0

我的数据类似于此:无序与belongs_to的参考的has_many关联到的has_many的

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中的一个ID:个人

谢谢!

回答

0

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

如果你想这样做,虽然,只是救人,你创建它们,因为这是当ID的将获得分配:

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

如果你担心数据库的一致性,包裹for循环和事务中的@team.save,所以如果一个失败,它们都会回滚。