In this eleventh part of a series on the Action Pack library for Rails, you'll learn another way to assign local variables inside a partial template, and how to control the logging in and out of users. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
More on Action Pack Partial Templates (Page 1 of 2 )
Explicit Local Variable Assignment in Partials
Automatic assignment is not the only way to assign local variables inside a partial template. The render method also accepts a hash of local variables identified by the :locals symbol. Imagine we have two instance variables: one containing a collection of articles and another one containing a collection of comments.
Any number of local variables can be assigned in this way, and any object can be set as the value. In the preceding example, not only will the partial have access to the @articles collection through the automatically assigned articles variable, it will also have access to the contents of the @comments collection using the local variable comments .
Rendering a Collection of Partials
Our first example of rendering the articles partial can actually be improved a bit. Notice how we’re iterating over the articles list inside the partial? Well, this is a common enough pattern that Rails has a better way of dealing with it. It’s called rendering a collection of partials.
Here’s how we would rewrite the list.rhtml file from the example:
And here’s how we would rewrite the _article.rhtml partial:
<li><%= article.title %></li>
Notice that we renamed the articles partial from the plural to the singular. Recalling what you know about automatic local variable assignment, this is because we want to deal with a single article. When you render using a collection, as we’ve done here, Rails will iterate over the given collection and yield the contents of the partial once for each iteration. The local variable article will become available inside the partial by virtue of the partial’s name.