0

I am looking at a book example. In the view section for a Products model, I see some code like this:

<table>
  <% @products.each do |product| %>
    <tr class="<%= cycle ('list_line_odd', 'list_line_even') %>">
      <td>
        <%= image_tag(product.image_url, class: 'list_image' %>
      </td>
    <td class ="list_description ">
       <dl>
           <dt> <%= product.title %> </dt>

Notice at the top it is using @products, while the last line in the table uses products instead of @products. Can someone explain this a little more?

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
Bohn
  • 26,091
  • 61
  • 167
  • 254

4 Answers4

1

In your example, @products is a collection that responds to the Enumerator#each method. In practice, this generally means an Array. You are then iteratively passing each element of @products into a block as the product variable.

In other words, product is a singular element taken from @products while executing a loop.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
1

@products contains a collection of Product objects. The product variable contains one instance of Product.

Victor Solis
  • 211
  • 1
  • 3
1

There are three types of variables in Ruby:

  • Regular variables, only available in their scope product in your sample code
  • Instance variables, available in a particular instance of a class. Each instance has its own sets of instance variables, @products in your example
  • Class variables, available in all instances of a class. These are also accessible directly (without an instance), @@variable (you do not have an example of this type)

The last line says product and is a completely different variable than @products. @products is filled by the class instance of your controller (probably called ProductsController). It is an list of products and the each() method is used to iterate through each list item. In the iteration loop product is used to specify the current product that is being iterated.

Veger
  • 37,240
  • 11
  • 105
  • 116
1

in the context of controllers and views you declare instance variables (starting with an @-symbol) in the controller to pass them to the views.

variables without an @-symbol at the beginning are variables that are only available within a limited scope, for example the elements of an iteration.

so you pass your @products from the controller to the views. after that you can iterate through the elements using product as a temporary identifier for the elements of your @products variable.

Marcel Hebing
  • 3,072
  • 1
  • 19
  • 22