Saturday, May 21, 2016

Adding ActiveRecord Relations

DISCLAIMER: This post is based on a true story. All coincidences with real situations or real people are completely intentional.

I am developing a small web system to a customer of mine. He use it to control the sales in his store. Nothing fancy. Just a few classes. A simple task, indeed. It took me just yesterday and today.

One of the requisites I received was that a certain customer of his store, with id=1, should always appear first in the customer's list, while the others should appear in the alphabetical order. In order to do so I did this at first:

It didn't work. It couldn't work, because it was a stupid idea. Even the most superficial test with rails c would have shown the absurdity of this idea. The variable a stores a single record, an instance of Customer model, while b is an ActiveRecord::Relation. Trying to add these two thing is like trying to add oranges and apples out of a good fruit salad.

When I got convinced of this fact I changed my code to:

And now it worked fine! Now I was adding to instances of the same class, ActiveRecord::Relation.

This kind of code, using the operator + directly saved me the processing time required to do something like:

This turns out to be even more important when you have a big number of records. This block would take a long time to run in this case, while the a + b operation is much faster.

Don't forget to check things at Rails console. You may save a lot of time doing a bit of research there when there is the slightest possibility of type conflicts or some similar thing.

And once more: Don't accept the first code you do as good enough. Always try to find a better way to do the same thing. There is always a better way.