Make your Rails views easy with select

Written by on

Recently, we were writing a new report for Tula. We needed to query for all users that had purchased a particular pass and when they purchased it. 

Here's what we came up with first: 

Well, that doesn't make it very easy to display in our view. We want a view as simple as this: 

Now that we had the simple view code with our favorite interface, we had to implement that interface. How would we do that? (By the way, you may notice we have date formatting in our view. You may want to try a decorator so your view is even simpler.)

By adding a select to our query, we can select all of the user attributes AND the pass attributes we need. We can add these attributes to the user (if you're familiar with SQL, we're essentially merging the join table attributes with the user being returned). You might want to read more about selecting specific fields.

 

Now, we've got a nice interface to work with that keeps our view super simple and not doing any extra work. We can access pass_name  and pass_purchase_date  directly from the user.

You should notice that we have a query in the controller. For simplicity, I kept it in the controller. You should really have this query in your model or better yet, in a single responsibility query object (see #4). 

If you have any questions or comments, please let us know in the comments section below.