skip navigation

Here you will find ideas and code straight from the Software Development Team at SportsEngine. Our focus is on building great software products for the world of youth and amateur sports. We are fortunate to be able to combine our love of sports with our passion for writing code.

The SportsEngine application originated in 2006 as a single Ruby on Rails 1.2 application. Today the SportsEngine Platform is composed of more than 20 applications built on Rails and Node.js, forming a service oriented architecture that is poised to scale for the future.

About Us

Skipping ActiveRecord While Keeping ActiveRelation

09/27/2012, 12:17pm CDT
By Patrick Byrne

When working with large amounts of records, it's sometimes a good idea to avoid creating ActiveRecord objects altogether.

Sometimes, like when you’re churning through lots of records for a large report, you don’t need all of that greatness. You just need to get the data out of the database. You could write some raw SQL queries and fetch them directly, but that’s cumbersome and ugly. Active Record gives you a lot of convenience in building queries. Wouldn’t it be great if you could use the convenience of Active Record’s Arel query syntax but skip the cost of building ActiveRecord objects.

I’ve got some great news. You can, with our find_as_hashes gem! Build your query beautifully, using scopes and other conveniences, but skip building the Active Record object and just receive the hash of attributes from the database by using “all_as_hashes” instead of “all” or “first_as_hash” instead of “first”.

 Some examples are in order:

We use this in a few places in our apps where performance is more important than having the benefits of ActiveRecord objects. In one report, iterating over 36,000 users, using all_as_hashes instead of all used 32% less memory and performed 17% quicker.

Tag(s): Home  Ruby  Performance