Taking advantage of Rails' counter in partials

As you may know, one of the many magic Rails moves is calling render on a model or collection of models, e.g., = render @products in a view. Rails will just look for a default partial that matches the model name, e.g., if it's a model called User, it'll look for users/_user.html.erb (or haml, or whatever). You can even control this behaviour by giving or overriding a model's method to_partial_path to something else, (yet another) e.g.:

def to_partial_path  

(yes, I know spaghetti is already plural... just illustrating a point)

Now rails will look for that model's partial in the views folder under spaghettis/_meatball.html.erb.

Now The Counter

Sweet, so now that we have that, there are a few things that Rails makes available in these model partials. One is a _counter variable with a prefix of the collection name that refers to how many times the partial has been rendered. For example, if you have a collection of objects in an instance variable @products, there will be a variable product_counter in each render of the partial. Cool but not a huge deal. For me, the cool part was Rails can handle a collection of mixed models.

What I mean by this is, say if you have a collection of Products and DealProducts that are mixed together in a collection variable @products. Even if Rails is rendering different partials that you've setup for each, it still keeps track of the product_counter correctly. This can be useful if you have to do something like set some tracking properties that are positionally based in a product grid. You can use product_counter to tell you what number the current rendered product is in the grid.

This was really helpful for me because I've had to do some pretty gnarly data-attributes on some product grids in the past. Without this counter I would have had to write some pretty heavy view helpers or some even worse Javascript to take care of it. But, like a lot of things, the good people on the Rails team thought of this ahead of time.

If you'd like to read more about the counter, or the other cool things available when rendering collections (spacers and layouts) check it out on the Rails guides: http://guides.rubyonrails.org/layoutsandrendering.html#rendering-collections


comments powered by Disqus