Lesson 3
Rails Views -- How Rails Renders Pages
To listen to the lesson, click the Play button on the left. You can also right-click on the download link to save the mp3 file, or you can subscribe in iTunes (just search for Learning Rails).
To read a transcript of the lesson, click the Transcript link on the left.
The heart of the lesson is the audio; these notes are supplementary. So please listen to the audio, or read the transcript, before making use of these notes.
Code Examples
In this podcast, we mention several bits of code that are hard to visualize in audio, so we’ve included them here. Refer to the transcript to see these examples in context.
For links to additional resources, scroll down past the code examples.
Embedded Ruby
Ruby code in a view template is preceded by <% and followed by %>. The enclosed text is what is called “embedded Ruby,” or ERb.
If the Ruby code is preceded by just <%, then the code is executed, but its output is not inserted into the HTML stream. For example, you might have Ruby code that says something like “if podcast title is not blank”. In real code, this would be:
<% if !podcast.title.blank? %>
For example, if we had a variable named title and we wanted its value to be inserted into the HTML, we’d write
<%= title %>
Last episode, we gave as an example a page listing all the episodes of this podcast. In this example, the variable that would be passed to the view would be an array of podcast objects.
The code to do so looks like this:
<% for podcast in podcasts %>
<h2><%= podcast.title %></h2>
<p><%= podcast.description %></p>
<% end %>
Partials
A partial is just a small view template that is meant to be included in another template, or in a layout. The statement that goes in the controller is:
render :partial => 'partial_name'
You can also use a partial when you want to repeatedly insert the same bit of markup, but using data from a series of objects. For example, consider our listing of podcast episodes. We can use a partial that displays the information for a single podcast. You could simply put that partial in a loop that executes it once for each podcast object, like this:
<% for podcast in podcasts %>
<%= render :partial => 'podcast' %>
<% end %>
(For simplicity, we’re ignoring here some details about how the podcast variable is passed to the partial.)
But Rails gives us a shortcut that makes this even simpler; in the “render partial” statement, we can refer to the array of podcast objects (which the controller provided), and the partial will automatically be repeated for each podcast in the array. Here’s the code:
<%= render :partial => 'podcast', :collection => podcasts %>
Rails Helpers
Instead of writing:
<a href = 'some_URL'>Text to be linked</a>
you can use the Rails link_to helper, like this:
<%= link_to 'Text to be linked', 'some_URL' %>
The link_to helper is more interesting when you use it to help you generate the URL, instead of specifying it explicitly. For example, you can specify the controller and action you want the link to invoke, and any parameters that you want to pass to it, and let link_to generate the URL. Dynamic generation of links is really preferable when it comes to flexibility and maintenance of your code. For example, you could write:
<%= link_to 'View Transcript',
:controller => 'podcast',
:action => 'view_transcript',
:id => podcast %>
Another common helper is image_tag. Instead of the usual
<img src = '/images/filename'>
you can write Ruby code that reads
<%= image_tag 'filename' %>
Rails assumes, by default, that all images are in a directory called images, so you don’t need to include the directory as part of the filename. You can also add additional parameters, such as alt text and image dimensions, using Ruby instead of HTML code, such as:
<%= image_tag 'filename',
:alt => 'Alt text goes here',
:height => 50, :width => 125 %>
DHTML with Rails
Here’s a simplified version of the code to observe the shipping adddress checkbox and call as JavaScript function when it is checked:
<%= observe_field 'shipping_address',
:function => 'show_shipping_address();' %>
(We haven’t shown here the code that defines the JavaScript function show_shipping_address(), which you could write in conventional JavaScript.)
With RJS (Ruby JavaScript), you can write something like:
<%= observe_field 'shipping_address',
:function => update_page {|page| page[:shipping_address].show} %>
There’s a bit of Ruby syntax there that we haven’t explained, but hopefully you get the idea. We’ve also ignored, for simplicity, the need to hide the shipping address if the box is unchecked.
Ajax with Rails
Here’s the observe_field statement that makes an Ajax call to the server to get the address:
<%= observe_field 'address_chooser',
:update => 'shipping_address',
:url => {:controller => 'user', :action => 'get_address'},
:with => 'address_chooser' %>
Resources for Further Learning
See the Lesson Page for lesson 1 for links to Ruby and Rails books and other resources.
If you want to get deep into the Ajax aspects of Rails, there’s one book devoted to that subject: Ajax on Rails
To learn more about the JavaScript frameworks included in Rails, visit their sites:

Reader Comments
32 comments
thank you for your work
From: Eila, 09/30/11 02:23 PM
very helpful was looking for something this easy and basic
Very Nice
From: Sandip Karanjekar, 08/10/11 03:43 AM
It's very good and helpful to me.
Very Good!
From: James Bolin, 05/27/11 08:28 PM
This does an excellent job of explaining some of the more obscure elements in Ruby that other sites have failed to do!
clean and clear
From: Garry Handa, 05/10/11 02:23 AM
Hi Guys, thats a wonderful effort ...and also very helpful to shine up the basics about RUBY THankss
Question
From: Alhassan ibrahim, 03/04/11 05:46 AM
Good afternoon Sir, i didn't see today lesson Thanks
Good job!
From: ree gee, 12/22/10 12:47 PM
Well thought out and very informative!
learning rails
From: rmc, 12/19/09 05:41 PM
hi, very nicely done. now i know a bit more about the interactions of these different rails objects. it's what's holding me up: who does what when and where? a bit of suggestion: for a piece of illustrative code, it will be nice to have a header on which file it belongs to and where in the file. i'm eager to read the next transcript. rmc
Thanks a lot
From: MaG, 11/07/09 07:17 PM
Its really a fantastic podcast.. Thanks a lot for this wonderful job you people doing.
lesson3
From: anilsai, 10/20/08 10:38 PM
thnk u its so nice.....i wanna know more abt the ajax....
Lesson#3
From: cherrian chin harada, 09/24/08 10:58 AM
Thank you once again! In which lesson will I need to download ROR to my computer? I think I tried once to download Ruby Forge one-step-installer but I don't think it wa successful, since it didn't appear in my program list. Is it a good idea to wait until we get to that lesson?
check_box observer
From: Vitaliy Khudenko, 09/02/08 02:42 AM
Thanks a lot fot this job!!! I think in accordance with that check_box id is 'use_shipping_address' the code of observer <%= observe_field 'shipping_address', :function => 'show_shipping_address();' %> should be actually changed to <%= observe_field 'use_shipping_address', :function => 'show_shipping_address();' %>
This podcast rolled too far off my known universe!
From: Kathleen, 07/30/08 08:12 AM
You guys are great, you're literate skills and sound quality are simply the best! I followed the first two podcasts and thought "These guys are Gods! and they're really going to take it home for me". This cast unfortunately rolled over into the usual approach in most Rails tutorials that "It's Easy!". We live in a knowledge centric culture where most folks forget that it's easy when you know how to do it, and hard when you don't! Firstly, you mention that when one declares a :yield that it can be either :left or :right. I've never seen this mentioned in any of the Rails books and cannot figure if these symbols (:left :right) must be declared by other layouts or css or what? Next, you go into the Javascript helper examples far too fast. You describe that one doesn't want to invoke layouts in certain instances but you don't show how these layouts are disabled? The examples you put forth are using the observe_field to effect @
Responding to Kathleen
From: Michael Slater, 07/30/08 01:57 PM
Sorry you got lost. You might find the screencasts starting at lesson 9 make it clearer. As to your question about having a symbol after the yield, :left and :right are just examples, you can put any symbol there that you want, and then in the view you can use "content_for :left do" to begin the block that creates the content for the left part of the layout. As for the JavaScript stuff, we're just trying to give you the flavor of it here, it takes some working with it to get the hang of it. Again, there are examples in the screencasts in later lessons.
Interesting and Useful!!!!
From: Davis, 07/22/08 04:25 AM
Many thanks for the simple explanation..However, it would be more practical if you added more examples :)
Credit to...
From: Thura, 07/20/08 03:30 PM
Thanks…showing the basic structure of ROR and easy to get the points.
Fantastic!
From: Chris, 07/16/08 11:31 PM
Thanks for putting this out there! I’m loving it on the commute to work.
Comprehensive Podcasts
From: Vivek, 07/15/08 05:34 PM
Many Thanks!! I’m lovin it…
good explanation
From: Rajesh F., 06/29/08 04:52 PM
Good explanation of each term.
Nice Work
From: jk, 06/22/08 10:56 PM
Your podcast rocks!
Nice goal.
From: Rafael Jamur, 06/10/08 02:53 AM
This is a very good job. I am happy too, for the transcript, becouse a speak in portuguese and, with that, I can understand the podcast (and train my english). Congrats!
Excellent!
From: Rich Webster, 05/18/08 12:57 PM
This is really great stuff. I just took a community college onlin class, and this is much clearer. Thanks!
Rails and Dojo
From: Michael Slater, 05/11/08 12:59 AM
Vijay, Rails has built-in support for Prototype and Scriptaculous. It can also be used with other JavaScript libraries, but in that case you’re on your own for integrating it in and providing Ruby wrappers for the JavaScript functions (or writing JavaScript directly in your view files). There are some independent efforts to provide Rails helpers for other libraries—try a google search on “Rails Dojo Helpers”, for example.
Good Article
From: Vijay, 05/10/08 09:10 PM
Makes a good read . I am very much impressed by the structure and contents of each article . For creating rich client UI what support does Rails offer ? say compatibility with DOJO ,etc
Good Article
From: Vijay, 05/10/08 09:10 PM
Makes a good read . I am very much impressed by the structure and contents of each article . For creating rich client UI what support does Rails offer ? say compatibility with DOJO ,etc
A request to improve usability
From: Claude Rousseau, 05/10/08 01:25 AM
First, thank you guys for this excellent work. I always use the transcripts along with the podcasts.
This is because I’m french (Québécois in fact), so I may have some trouble following the spoken comment.
Another reason is, as you suggest, to look at the code snipets.
Sometimes I’d like to be able to pause on the fly and either read the concept, or have a long look at the code.
Doing this is a bit cumbersome, because I have to scroll up the page to access the control… Could you modify your layout so the podcast control widget follows the text when I’m scroling down? That would be very handy.
Thanks again!
A request to improve usability
From: Claude Rousseau, 05/10/08 01:25 AM
First, thank you guys for this excellent work. I always use the transcripts along with the podcasts.
This is because I’m french (Québécois in fact), so I may have some trouble following the spoken comment.
Another reason is, as you suggest, to look at the code snipets.
Sometimes I’d like to be able to pause on the fly and either read the concept, or have a long look at the code.
Doing this is a bit cumbersome, because I have to scroll up the page to access the control… Could you modify your layout so the podcast control widget follows the text when I’m scroling down? That would be very handy.
Thanks again!
ajax help
From: Steve Nelson, 05/03/08 03:39 AM
Thanks Michael! I’ve got edition 1 and 2 of AWD – maybe I’ll look more closely at edition 2 before trying the beta pdf – I can’t stand reading complex stuff on screen without the ability to turn down corners and write in margins! I probably missed that good stuff in David’s book because it wasn’t Ajax in particular I was interested in. I know your podcast describes inserting stuff after a call to the database without a page refresh. But there’s a lot of useful stuff the frameworks can do without the complexity of ajax added on top – in the example I described I was working on a contact management app. I wanted the basics (name, phone, email) to be shown immediately and additional details (mail, notes etc) revealed on request by clicking a text link that said something like “show details”. I had already fetched that data so I just wanted to use scriptaculous to do an animated reveal. It was really tough to find references online as to what all was available to me and how to implement it. Anyway – thanks again for your interest and advice. Looking forward to listening to episode 4! Steve.
Learning Rails Ajax functions
From: Michael Slater, 05/02/08 09:32 AM
Steve, I agree that it is challenging to sort out the Ajax functions from the docs. The Prototype and Scriptaculous docs don’t describe the Rails helpers, and the Rails helper docs don’t fully explain the prototype and scriptaculous functions.
These docs really aren’t intended as tutorials, and while better docs might come closer to being usable for a new user, I find that books and online articles are an essential part of the learning process. I would not attempt to learn to use the Ajax functions in Rails from the API docs.
I’ve found the Ajax on Rails book to be helpful for understanding how it all works together. There are two books out on Prototype and Scriptaculous, and they too are useful, though they don’t describe the Rails helpers. The Rails classic Agile Web Development with Rails has a good chapter on Ajax basics, and this part of the framework hasn’t changed too much for Rails 1.2, which the current print book covers. If you buy the pdf book now you can get version 3, covering Rails 2, as it is produced.
helper help
From: Steve Nelson, 05/01/08 11:43 PM
Hi; I’m really enjoying the podcasts so far. Screencasts are wonderful things too, but I can listen to a podcast in the car! You take pains to point out how RoR facilitates using the big complex javascript frameworks but… if I don’t know the intimate ins and outs of prototype, scriptaculous OR RoR… where the heck can I find documentation on what can be done and how to invoke all the goodness? Rails docs seem to point to the javascript frameworks, and they point back to the Rails documentation and a guy like me can’t make head or tails out of how to make use of the potential. On a project I was working on I wanted a div to slide down to reveal additional content. The “blind” animation was what I wanted but it was a dreadful pain (and significant investment of time) to track down how to do it. Thanks for any tips there!
that's great!
From: zain alabdin tawfiq, 04/15/08 03:39 AM
that’s great Michael! thanks for your time and effort
Code examples
From: Michael Slater, 04/13/08 08:33 AM
Thanks for the suggestion. We don’t have full code examples for this lesson, but from Lesson 9 forward, which begins the screencast series, we provide the complete application code.
Thanks! and a suggestion
From: zain alabdin tawfiq, 04/13/08 08:27 AM
Hi! thanks for the lovely free lesson… I suggest you provide example pages with each example of rails code you show… i mean include an attachment of how the rhtml code would look like in this lesson for example. thanks again