Friday, October 26, 2012

Rails 3.2 Double-Post on adding AJAX

If you're seeing a double-post after adding AJAX, and you have ever precompiled your assets, try deleting everything from public/assets.

Wednesday, October 24, 2012

Rails 3.2.8 AJAX super-basic example

This is an updated-for-rails 3.2.8 super-simple AJAX tutorial, for people who have already followed a basic rails tutorial. I found a lot of rails AJAX tutorials but just enough has changed since 3.2.8 I wanted to show an updated version.
First, my versions of things I am using!

carmen@ubuntu:~/ws$ uname -a
Linux ubuntu 3.2.0-31-generic #50-Ubuntu SMP Fri Sep 7 16:16:45 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
carmen@ubuntu:~/ws$ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]
carmen@ubuntu:~/ws$ rails -v
Rails 3.2.8

Now on to the good stuff!

rails new ponies
cd ponies
rails generate scaffold Pony name:string profession:string
rake db:migrate
rails s

Make some ponies...

http://localhost:3000/ponies/new

Update your destroy line in index.html.erb. Add :remote => true, :class => 'delete_pony' to app/views/ponies/index.html.erb. The line should now look like:

    <%= link_to 'Destroy', pony, method: :delete, data: { confirm: 'Are you sure?' }, :remote => true, :class => 'delete_pony' %> 

Create a file, destroy.js.erb, put it next to your other .erb files (under app/views/ponies). It should look like this:

$('.delete_pony').bind('ajax:success', function() {  
        $(this).closest('tr').fadeOut();
});  

Add format.js { render :layout => false } to your controller (app/controllers/ponies_controller.rb). Your destroy method should now look like this:

  # DELETE /ponies/1
  # DELETE /ponies/1.json
  def destroy
    @pony = Pony.find(params[:id])
    @pony.destroy

    respond_to do |format|
      format.html { redirect_to ponies_url }
      format.json { head :no_content }
      format.js   { render :layout => false }
    end
  end

Restart your server, and click 'Delete' on some ponies (Preferably Rainbow Dash), and viola, they just fade out! In Rails 3.2.8.