title: Ruby on Rails: Creating child objects
body: <p>I'm sure this is a very simple question, but I'm just a newbie so...</p>
  
  <p>I have a model, Game, which <code>has_many :piles</code>. Pile, in turn, <code>has_many :cards</code>. I'm able to populate the Piles and Cards at creation of the Game, so my code at present looks something like:</p>
  
  <pre><code>class Game &lt; ActiveRecord::Base
    has_many :piles
  
    def after_create
      1.upto(4) do |num|
        Pile.new("game_id" =&gt; id, "contents" =&gt; "c_type_#{num}")
      end
    end
  end
  
  class Pile &lt; ActiveRecord::Base
    has_many :cards
    belongs_to :game
  
    def after_create
      1.upto(10) do |num|
        Card.new("pile_id" =&gt; id, "value" =&gt; num)
      end
    end
  end
  
  class Card &lt; ActiveRecord::Base
    belongs_to :pile
  end
  </code></pre>
  
  <p>Now this is all very well, but it feels wrong to be passing <code>"game_id" =&gt; id</code> when ActiveRecord <em>knows</em> that game_id is the foreign key and should refer to the parent game. But if I leave it off, the foreign key ends up unset. Is there a better way to do this?</p>
  
  <p>(For a bonus, probably simpler, question; suppose Game also <code>has_one :monkey</code>. How best do I create the monkey from within the Game model?)</p>