views:

18

answers:

1

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!

A: 

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.

Karl