title: Rails: multi level nested Forms (accepts nested attributes)
body: <p>I am creating simple blog level application. below are my models.</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    attr_accessible :name,:posts_count,:posts_attributes , :comments_attributes
    has_many :posts
    has_many :comments
    accepts_nested_attributes_for :posts , :reject_if =&gt; proc{|post| post['name'].blank?}  , :allow_destroy =&gt; true
  end
  
  
  class Post &lt; ActiveRecord::Base
    attr_accessible :name, :user_id ,:comments_attributes
    belongs_to :user
    has_many :comments
    accepts_nested_attributes_for :comments
  end
  
  class Comment &lt; ActiveRecord::Base
    attr_accessible :content, :post_id, :user_id
    belongs_to :user
    belongs_to :post  
  end
  </code></pre>
  
  <p>I am trying to create user,post and comment in one form by using <code>accepts_nested_attributes_for</code> feature of rails. Below is my controller and view code.</p>
  
  <p>Controller-----------</p>
  
  <pre><code>class UsersController &lt; ApplicationController
    def new
      @user = User.new
      @post = @user.posts.build
      @post.comments.build
    end
  
    def create
     @user = User.new(params[:user])
     @user.save
    end
  end
  </code></pre>
  
  <p>Form----------</p>
  
  <pre><code>&lt;%= form_for @user do |f| %&gt;
      &lt;%= f.text_field :name %&gt;
  
      &lt;%= f.fields_for :posts do |users_post| %&gt;
          &lt;br&gt;Post
          &lt;%= users_post.text_field :name  %&gt;
          &lt;%= users_post.fields_for :comments do |comment| %&gt;
               &lt;%= comment.text_field :content %&gt;
           &lt;% end %&gt;
      &lt;% end %&gt;
      &lt;%= f.submit %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>With the above code i am successfully able to create new user,post and comment but the problem is that i am not able to assign newly created user to newly created comment.when i checked the newly created comment into the database i got below result.I am getting user_id field value of "nil".</p>
  
  <pre><code>#&lt;Comment id: 4, user_id: nil, post_id: 14, content: "c", created_at: "2014-05-30 09:51:53", updated_at: "2014-05-30 09:51:53"&gt;
  </code></pre>
  
  <p>So I just want to know how we can assign newly created comment to newly created user???</p>
  
  <p>Thanks,</p>