Today I Learned
How to use an index on a Collection's Partial
Posted on February 21, 2018

When iterating through a collection in a rails view, I typically use a block to do so right in my view.

If I need different id’s in the DOM for each element, it’s quickly achievable with the with_index method which provides the index of each item as it iterates.

<!-- index.html.erb -->
  <% @products.each.with_index do |product, index| %>
    <li id="product<%= index %>"><%= %></li>
  <% end %>

While with_index works when you’re iterating through a collection within your view, you but how would you create different id’s in the DOM if you’re rendering your collection within a partial?

According to Local variables in Rails documentation, when you’re rendering a collection with a Rails partial, you can use a counter as you iterate over that collection.

That same example rendering the collection with a rails partial would look like.

<!-- index.html.erb -->
  <% render partial: "product", collection: @products %>

<!-- _product.html.erb -->
<li id="product<%= product_counter %>"><%= %></li>