Skip the navigation

First Ruby, now ... Ajax on Rails! Here's how

By Scott Raymond
March 15, 2007 12:00 PM ET

This article is excerpted from Ajax on Rails, copyright 2007 O'Reilly Media Inc., all rights reserved. Used with permission from O'Reilly Media Inc.

Doing vanilla Ajax without the support of any extra libraries or helpers isn't the trick it's often portrayed to be. The idea of writing more than a dozen lines of code to do the simplest possible task is off-putting. Rails provides a huge amount of power for doing complex Ajax interactions with very minimal code.

Ajax on Rails
Ajax on Rails
Scott Raymond
Rails provides convenient integration with Prototype (a JavaScript framework bundled with and developed alongside Rails), in the form of helper methods that generate Prototype calls. It's possible to do Ajax without writing any JavaScript, using the link_to_remote() helper method.

First, we need to back up a little and look at Rails' system for handing views.

ERb Basics

If you've ever used PHP, ColdFusion, ASP, JSP, or something similar, this will be a familiar concept. Embedded Ruby (ERb) lets you mix Ruby snippets into your HTML. ERb defines a set of special tags that get interpreted as Ruby; everything else is assumed to be plain HTML and is passed through untouched. Here are the special tags:

<%= %> The most common one, this holds a Ruby expression—which is output in place of the tag.
<%= -%> Works just like the above but suppresses newline characters from the output after the tag, which allows for cleanly organized templates without extraneous whitespace in the HTML output.
<% %> This holds a piece of Ruby code but doesn't output anything.
<% -%>
Works just like the above but suppresses newline characters after the tag.
<%# %>
This is a Ruby comment, which is ignored and nothing is output.

Let's look at an example.
Our Commenting Policies