O'Reilly logo

Ajax on Rails by Scott Raymond

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Bringing Rails into the Picture

Rails provides convenient integration with Prototype, in the form of helper methods that generate Prototype calls. Next we’ll discover how 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.

Remember our discussion of MVC in Chapter 1? Here is where it begins to come into play. Typically, a controller will receive a request for a page, and assemble the data needed for the view. In Rails, that data is put into instance variables (which are recognizable by the ugly @ sign that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required