Rails makes a counter variable available within partials that are rendered with a collection. This variable follows the name of the collection. A @users
collection has a counter called user_counter
. The counter works like the index on an each loop. It counts the number of times a partial has been rendered. Let’s look at an example.
In index.html.erb
we render a partial with a collection:
1
<%= render partial: 'user', collection: @users %>
Inside, the partial can use user_counter
:
1
<p>partial has been rendered: <%= user_counter %></p>
Here’s how the page renders for a collection of 3 users:
1
2
3
4
5
partial has been rendered: 0
partial has been rendered: 1
partial has been rendered: 2
What can a partial counter be used for
There are at least two uses for the partial counter: displaying an index and debugging.
1) We can use the counter for display purposes. For example, on a hotel booking site we may want to display an index against each hotel, for the customer to use as a visual reference. With an ActiveRecord backed collection this is unnecessary because there’s a database ID but it may be useful for more primitive collections, such as arrays.
2) Overuse of partials is a common cause of Rails performance issues. We have some different options for debugging this problem, such as using the Rails logs or third party tools, but the partial counter is also useful to see how many times a particular partial is being rendered.