title: Ajax based micropost's comments (Ruby on Rails)
body: <p>I have ajax based micropost's comments on the user page. It works, but not correctly. When I submit a new comment to <strong>any</strong> micropost, it always posts to the <strong>last</strong> micropost. Then, if I refresh the page by "F5", everything falls into place - the new comment is in the correct micropost. Thanks in advance.</p>
  
  <p><strong>comment.rb</strong></p>
  
  <pre><code>class Comment &lt; ActiveRecord::Base
    attr_accessible :comment_content
    belongs_to :user
    belongs_to :micropost
  end
  </code></pre>
  
  <p><strong>comments_controller.rb</strong></p>
  
  <pre><code>class CommentsController &lt; ApplicationController
    before_filter :signed_in_user, only: [:create, :destroy]
  
     def create
      @micropost = Micropost.find(params[:micropost_id])
      @comment = Comment.new(params[:comment])
      @comment.micropost = @micropost
      @comment.user = current_user
        respond_to do |format|
        @comment.save
             format.html { redirect_to current_user }
             format.js
        end
     end 
  end
  </code></pre>
  
  <p><strong>_micropost.html.erb</strong></p>
  
  <pre><code>&lt;tr&gt;
    &lt;td class="micropost"&gt;
      &lt;span class="content"&gt;&lt;%= wrap(micropost.content) %&gt;&lt;/span&gt;
      &lt;span class="timestamp"&gt;
      Posted &lt;%= time_ago_in_words(micropost.created_at) %&gt; ago.
      &lt;/span&gt;
      &lt;%= render 'shared/comment_form', micropost: micropost %&gt;
     &lt;div id="comments"&gt;
       &lt;%= render micropost.comments %&gt;
     &lt;/div&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
  </code></pre>
  
  <p><strong>_comment_form.html.erb</strong></p>
  
  <pre><code>&lt;%= form_for ([micropost, @comment]), :remote =&gt; true do |f| %&gt;
  &lt;%= render 'shared/error_messages', object: f.object %&gt;
  &lt;%= f.text_area :comment_content, :size =&gt; "40x2" %&gt;
    &lt;button class="btn" type="submit"&gt;
      Comment
    &lt;/button&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p><strong>_comment.html.erb</strong></p>
  
  <pre><code>&lt;span style="width: 100%; background:#dff0d8"&gt;&lt;%= wrap(comment.comment_content) %&gt;&lt;/span&gt;
  &lt;span class="timestamp"&gt;
   Posted by &lt;%= comment.user.name %&gt; &lt;%= time_ago_in_words(comment.created_at) %&gt; ago.
  &lt;/span&gt;
  </code></pre>
  
  <p><strong>create.js.erb</strong></p>
  
  <pre><code>$('#comments').html("&lt;%= escape_javascript(render(:partial =&gt; @micropost.comments)) %&gt;");
  </code></pre>