Laurence Laurence - 1 year ago 75
Ajax Question

rails ajax overwriting all partials when refreshing page

I was making a simple variation of the simple example of ajax in rails:

I am trying to create a user show view in which new posts are created upon pressing a button. These posts are all listed below the user on the same show page and appear upon creation.

The posts are created fine and shown correctly on the page, however when I refresh the page my

@post =

Overwrites all the previously created posts giving each of them a nul id.
Also, is it correct to place the create.js.erb in the views folders, or should it go in the assets/javascripts folder?

Here are my files:


def show
@user = User.find(params[:id])
@posts = Post.all
@post =


<%= "user-id: #{}" %>

<ul id="posts">
<%= render :partial => @posts %>

<%= form_for(@post, remote: true) do |f| %>
<%= f.hidden_field :user_id, :value => %>
<%= f.submit %>
<% end %>


def create
puts params[:post][:user_id]
@user = User.find(params[:post][:user_id])
puts @user
@post =
respond_to do |format|
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.js {}
format.json { render json: @post, status: :created, location: @post }
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }

def index
@posts = Post.all
@post =


<li><%= %></li>


$("<%= escape_javascript(render @post) %>").appendTo("#posts");

Answer Source

The Problem

The reason why your partial is rendering all new posts is because you are using the instance variable @post instead of the local variable post inside your partial.

In your UsersController#show action, you set @post = When you render <%= %> inside the partial, you are referencing that same variable which comes from the controller and was set to a new post.

It seems that all the previously created posts are being "null'ed" out, but it's really just that you are continuously rendering a new post, not the existing ones.

The Solution

You need to update your partial to use a local variable, not the instance variable.

<li><%= %></li>

This local variable is automatically provided to you by Rails when you render a collection of records like this

<%= render @user.posts %>

or alternatively

<%= render partial: "posts/post", collection: @user.posts %>

How to Avoid in the Future

This is a really common mistake and can be easy to miss.

For this reason, my recommendation is to stop using instance variables in partials altogether.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download