benoitr
benoitr

Reputation: 6105

Ajax create action: partial doesn't update without a page refresh

I have a text field in a form_tag on my index page that should create a new "gallery" with ajax. Unfortunatly my partial (which loops through all the galleries) doesn't update without a page refresh.

If I submit two times the form it renders feed until the next to last.

I saw several SO posts but it doesn't seem to give me any answer in this case:

rails-3-ajax-update-partial-doesnt-work-without-page-refresh

rails-3-ajax-newsfeed

Please see my code:

Controller

controllers/admin/galleries_controller.rb

def create
  @galleries = Gallery.all
  @gallery = Gallery.create(:name => params[:name])
  respond_to do |format|
    if @gallery.save
      format.html { redirect_to admin_galleries_path }
      format.js
    else
      flash[:notice] = "Gallery failed to save."
      format.html { redirect_to admin_galleries_path }
    end
  end
end

Views

create.js.erb

# alert("ajax works"); rendered the alert box correctly
$("#galleries").html("<%= escape_javascript(render(@galleries)) %>");

admin/galleries/index.html.erb

<%= render "form" %>
<ul id="galleries">
  <%= render @galleries %>
</ul>

admin/galleries/_form.html.erb

<%= form_tag(admin_galleries_path, :method => :post, :remote => true) do %>
  <%= text_field_tag(:name) %>
  <%= submit_tag("Create") %>
<% end %>

admin/galleries/_gallery.html.erb

<li><%= gallery.name %></li>

logs

Rendered admin/galleries/_gallery.html.erb (0.6ms)
Rendered admin/galleries/create.js.erb (1.4ms)
Completed 200 OK in 18ms (Views: 7.9ms | ActiveRecord: 3.6ms)

Thanks a lot for your help!

Upvotes: 1

Views: 740

Answers (1)

rdvdijk
rdvdijk

Reputation: 4398

I think you need to swap these two lines:

    @galleries = Gallery.all
    @gallery = Gallery.create(:name => params[:name])

Otherwise, @galleries will not include the newly created Gallery.

Upvotes: 4

Related Questions