Rails: Refactor an ActiveRecord Query

0
135

Let’s refactor a clunky ActiveRecord query, shall we?

First, let’s look at our ActiveRecord query. It’s not very good is it? Don’t worry, we all write something like this at some point. Usually, it’s a first proof of concept type code until we can get around to cleaning it up.

https://gist.github.com/thehashrocket/bbfd232c6bab81f1a8302583e5eb0b40.js

Now, let’s optimize it a bit, see if we can clean it up and make it more presentable.

https://gist.github.com/thehashrocket/d8a8eb6a1b6644c7eaf223e785859df8.js

Ok, that’s better. What happens if we hit our unique constraint in the database, though? That would suck. Better take care of that as well.

https://gist.github.com/thehashrocket/c1237d60a9e26c9382c8083a3a818538.js

This will add new records but silently fail on duplicate attempts in the Track model.