July 9, 2014

AJAXify your Rails web in three steps

Creating fully AJAX website in Rails is easy thanks to Turbolinks and Server generated JavaScript Responses.

Turbolinks are enabled in Rails 4 by default. But they handle just standard GET requests (i.e. clicking on the links). If you need it with some other method (for example DELETE for sign_out link, or POST for html form), then it will be followed without Turbolinks with full page reload.

But it is easy to fully ajaxify all user actions just in three steps.

1) Add remote: true to your links and forms

<%= form_tag signin_path, method: :post, remote: true do |f| %>
  ...
<% end %>

2) Change redirect_to in your controllers to redirect_via_turbolinks_to

redirect_via_turbolinks_to will just manually trigger Turbolinks to load given page with Turbolinks.visit(path).

class SessionsController < ApplicationController
  def create
    user = User.find_by_email(params[:email])

    if user && user.authenticate(params[:password])
      sign_in user
      redirect_via_turbolinks_to root_path
    else
      flash.now[:warning] = 'Wrong email/password combination'
      render 'new'
    end
  end
end

3) Create CoffeeScript template which will handle non redirect actions

# app/views/sessions/new.js.coffee
$('form').replaceWith('<%= j render('form') %>')

And you are done. Now whole sign in process is fully ajaxified.

For more detailed information check Turbolinks on GitHub and dhh's post on SJR.

Hey there!

My name is Patrik Bóna and I am the only programmer at Memberful. This blog is kind of dead, but I just started my own Ruby on Rails screencast. Follow me on Twitter if you want to be notified about my newest videos.