Simple rendering of collections in Rails
I finally graduated from NYCDA’s web development bootcamp, caught up on some much needed sleep, and started looking through the code that I was furiously writing in those final weeks. On one hand, I’m proud of what I made in such a short timespan. On the other hand, it’s clear that there’s plenty of room for improvement. In my rush to absorb everything, I missed some helpful patterns and techniques, so now I’m taking a more careful approach and refining what I’ve got.
For example, I just learned that I had been overcomplicating the rendering of a collection in a Rails view. In my Three Good Things project, the common view displays a collection of short text samples (or
things) to the user:
A feed of the good things that happened during anonymous users’ days
Within the view, here’s the section of code that displayed that collection of
The view has access to an array of things, called
@things. I call
each on that array, and iterate through it. At each iteration, I render a partial (
things/_thing.html.erb) using the
thing object at each spot in the array.
While that’s fine and good, it misses out on some Rails magic using partial paths, as described in this Thoughtbot post: Rendering Collections in Rails. In short, you can achieve the same effect with simply:
For each element in
@things, if the element is an object that also has a matching partial (based on the object’s name),
render will automatically find and use that matching partial. That works perfectly here, because
@things is just a collection of
Thing objects, and I have a matching partial at
views/things/_thing.html.erb. Even cooler, it still works with hetergeneous collections. If there was a lone
User object in that collection and I had defined a partial for users, that would be rendered just as easily. Awesome!