title: Saving an active record, in what order are the associated objects saved?
body: <p>In rails, when saving an active_record object, its associated objects will be saved as well. But has_one and has_many association have different order in saving objects.</p>
  
  <p>I have three simplified models: </p>
  
  <pre><code>class Team &lt; ActiveRecord::Base
    has_many :players
    has_one :coach
  end
  
  class Player &lt; ActiveRecord::Base
    belongs_to :team
    validates_presence_of :team_id
  end
  
  class Coach &lt; ActiveRecord::Base
    belongs_to :team
    validates_presence_of :team_id
  end
  </code></pre>
  
  <p>I expected that when <code>team.save</code> is called, team should be saved before its associated coach and players.</p>
  
  <p>I use the following code to test these models:</p>
  
  <pre><code>t = Team.new
  team.coach = Coach.new
  team.save!
  </code></pre>
  
  <p><code>team.save!</code> returns true.</p>
  
  <p>But in another test:</p>
  
  <pre><code>t = Team.new
  team.players &lt;&lt; Player.new
  team.save!
  </code></pre>
  
  <p><code>team.save!</code> gives the following error:</p>
  
  <pre><code>&gt; ActiveRecord::RecordInvalid:
  &gt; Validation failed: Players is invalid
  </code></pre>
  
  <p>I figured out that <code>team.save!</code> saves objects in the following order: 1) players, 2) team, and 3) coach. This is why I got the error: When a player is saved, team doesn't yet have a id, so <code>validates_presence_of :team_id</code> fails in player.</p>
  
  <p>Can someone explain to me why objects are saved in this order? This seems not logical to me.</p>