ActiveRecord v Raw SQL
For the past few weeks, I have been working on a Ruby on Rails project. I left a couple features out that have been irking me for months. I couldn’t quite get a scope to work exactly how I intended. I wanted to revisit this problem after I’ve had a chance to learn a bit more about some other languages. The most recent rabbit hole I have gone down has been about the use of raw SQL or lack thereof.
I don’t plan on going into a ton of detail on ActiveRecord today but to put it broadly, it is an object relational mapping framework. Using a named scope, you can access data in a similar manner to using an SQL query. For anyone who is comfortable with SQL, it can be a knee-jerk reaction to want to write SQL queries or “raw SQL” into Rails. Let us take a look at some pros, cons and exceptions to adding raw SQL to a Rails project.
First, the main consensus points to avoid raw SQL into your applications. It’s not really standard but that does not mean it is completely banned. We will take a look at a few exceptions but let’s first take a look at the cons. One of the first good examples I have come across states that writing in AR (ActiveRecord) will save time for the current and future colleagues. This is applicable for groups or companies who are all working with Rails. The next person to work on that code might not be a pro at SQL but it would be more probable that they are versed in Rails. Another argument that has been posed thinks that the computing power should be done by Ruby opposed to SQL. This logic can be debated but again, consensus points to leaving the computing power within Ruby. Lastly, if you think you need to write a query in raw SQL, you are probably not versed enough in how to write ActiveRecord queries. I am not saying there is no reason you should write raw SQL, I am saying that in most cases, the same can be achieved in ActiveRecord if you have a solid grasp of proper syntax.
As discussed above, there are some pros to writing raw SQL and when the exception fits. First, this is not a steadfast rule. Some workplaces may opt for raw SQL. Whether it is preference or a logical decision due to their ORM, sometimes raw SQL can fit. If you have some complex sub queries, this is an example of working harder than you need to to understand ActiveRecord. Where that complex sub query could be written in ActiveRecord, the time spending on how to replicate that can just be a waste of time.
The last note I want to leave you on if you are still debated on which you should use. If you are leaning towards raw SQL, take a look at the Arel gem. It is a super helpful gem that can bridge the gap with what you might need. It has over 250 million downloads and still seems pretty active pumping out new updates. I hope this helps with your current and future projects!