small medium large xlarge

20 Jun 2012, 13:05
Andrew Gellene (33 posts)

In chapter 11 page 131

“The render() method will iterate over any collection that is passed to it.”

This could use more information on what is going on. I think what is happening is the render command is replaces this:

<% @cart.line_items.each do item %>

This is an iteration over a the line items and when you call <% render @cart.line_items %> it is somehow replacing the .each do and iterating over the line_items to populate this:

<%= line_item.quantity %>×</td>

<%= line_item.product.title %></td>

<%= number_to_currency(line_item.total_price) %></td>

But notice the change which is not pointed out in the book :

Before you the “.each do item ” set up the variable item to be passed to the following: <%= item.quantity %>× <%= item.product.title %> <%= number_to_currency(item.total_price) %>

now item.quantity is replaced by line_item.quantity and so on so that the iterating of line_items called by the magic render method can find the quantity and title in the line_item database.

if this is the wrong way of thinking of render then please correct me.

27 Feb 2013, 01:10
Xavier John (21 posts)

I am having trouble understanding render as well. In the rails doc, render does not take any object as parameter

Basically I want to render the object in different ways, and I am trying to figure out how to tell render which erb to use.

27 Feb 2013, 02:00
Sam Ruby (633 posts)

The way to tell render to use a different template is via:

render template: 'name'

The way to pass objects to a template is to set instance variables (staring with an “@” sign) and reference them within the template.