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.
Now, let’s optimize it a bit, see if we can clean it up and make it more presentable.
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.
This will add new records but silently fail on duplicate attempts in the Track model.