Tutorials

ActiveRecord exists? and blank? under the hood.

cog

When should I use exists? or blank? to check records existence? Does this choice has an impact on our application?

Asking those questions is a good sign of curiosity! So we will see together how those methods work under the hood and without a long introduction let’s unpack ActiveRecord and dive deep into the source code.

Putting exists? under the scope:

Let’s try to call exists? on a Post model:

We will notice this output line in the console:

So let’s try to see the code behind it to understand how it works, I tried to share only the relevant snippets of code, for reference please visit this file for ActiveRecord 5.2

and we need to check select_value method to get the complete picture:

Now we can understand how ActiveRecord is building the exists? query. We can also see that the query check whether there is a row or not  overlook columns by using:

There are different discussions and opinions about this query, but for us, it’s important to know that this check doesn’t instantiate records and perform the check by confirming the existence of a row in our model table.

Putting blank? under the scope:

The reference source code for the simplified snippet below can be found here.

and the code for find_by_sql method:

We checked together how blank? method loads records to perform this check. But before saying that we should always use exists? let’s step back and analyze the shared code. I suggest checking the load method again, it loads the records from the database only if they haven’t been loaded already.

That comment is very important to grasp. For example, if we are performing an existence check on records that we need as part of the application logic then we should use blank? which results in hitting the database once for the select query. But if we opted for exists? we will end up by hitting the database twice, the first query to perform the check and the second one to fetch the data.

Conclusion

Inspecting the source code of those methods was a good exercise to improve our knowledge and understand how the framework is working under the hood.

We should remember these two points:

  • Use blank? if you need to use the records in the application logic.
  • Prefer exists? if you care only about the existence check.

That’s it, so have fun and keep coding 🙂

Tagged , , , , ,