title: What's the Rails way to save an object with associatons?
body: <p>I have a couple of classes with a usual one-to-many relationship, like:</p>
  
  <pre><code>class Blog &lt; ActiveRecord::Base
    has_many :posts
  end
  
  class Post &lt; ActiveRecord::Base
    belongs_to :blog
    validates :blog_id, presence: true
  end
  </code></pre>
  
  <p>when I build a blog and add to it a bunch of posts:</p>
  
  <pre><code>blog = Blog.new
  blog.posts = [Post.new, Post.new]
  </code></pre>
  
  <p>I cannot just save the blog, like this:</p>
  
  <pre><code>blog.save
  </code></pre>
  
  <p>because blog_id in the posts is blank, so validation for the posts are failing. I thought Rails was <em>smart</em> enough to either check the id or the presence of the object, but it isn't.</p>
  
  <p>What's the proper Rails way to solve this? Something better than:</p>
  
  <pre><code>saved = true
  Blog.transaction do
    saved &amp;&amp;= @blog.save
    if saved &amp;&amp; params[:blog][:posts].responds_to?(:each)
      params[:blog][:posts].each do |post|
        p = Post.new({blog: @blog}, without_protection: true)
        saved &amp;&amp;= p.save
      end
    end
  end
  </code></pre>