Unobtrusive AJAX with Rails 3.1

Since Rails 3.0 release, Unobtrusive Javascript has introduced in building Rails application. It’s a technique for separating the behavior of a web application from its content. It helps us to implement a web application that works for clients with and without enabled javascript. If users don’t have enabled javascript, then it works just traditional web application.

AJAX with Rails, if you have some experiences with RJS in previous versions of Rails, then you will not see many differences when you implement AJAX in Rails 3.1. One different is you create template in javascript or coffee-script instead of RJS. Let’s see how we implement application below:

Unobtrusive AJAX with Rails 3.1

Add js respond format to comments controller app/controllers/comments_controller.rb

  def index
    @comments = Comment.all

  def create
    @comment =[:comment])

    respond_with @comment, :location => comments_url

Implement views app/views/comments/index.html.erb with remote form

<div id="comments_count"><%= comments_count %></div>

<div id="comments">
  <%= render @comments %>

<h3>Add your comment:</h3>

<%= form_for, :remote => true do |f| %>
  <%= f.error_messages %>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
    <%= f.label :content, "Comment" %><br />
    <%= f.text_area :content, :rows => '12', :cols => 35 %>
  <p><%= f.submit %></p>
<% end %>

<%= %> on <%= comment.createdat.strftime(’%b %d, %Y at %I:%M %p’) %> <%= simple_format comment.content %>

Add javascript or coffeescript template, I prefer (app/views/comments/ to handle ajax request


$('#comments_count').html '<%= comments_count %>'

The complete source is on Github. So feel free to checkout and run it to see in action.