
Stop Killing Your Database: 5 ActiveRecord Tips for Faster Rails Apps
In this article, I want to share my journey with ActiveRecord. When I first started with Rails, I thought ActiveRecord was just "magic" to save data to the database. But after working on larger projects, I realized there is so much more to it. It is very easy to write code that works, but it is also very easy to write code that makes your app slow. Here are the levels of ActiveRecord knowledge, moving from simple queries to more advanced optimizations. LEVEL 1: The Basics (Chaining) Most beginners know find and where . But the cool thing about ActiveRecord is that you can chain these methods together endlessly until you actually ask for the data. For example, if you want to find users who are active and signed up recently: # Instead of doing this users = User . where ( active: true ) recent_users = users . where ( 'created_at > ?' , 1 . day . ago ) # You can chain it nicely User . where ( active: true ). where ( 'created_at > ?' , 1 . day . ago ) This generates only one SQL query. Rail
Continue reading on Dev.to
Opens in a new tab




