rails

Performant Queries with ActiveRecord Includes

Let’s say we have a User model and each user has many Posts. To get a list of all of the posts for a user we may do something like:

posts = User.all.map { |u| u.posts }

This is perfectly reasonable and will work for a majority of cases. However, if you have a large number of users and posts this can be a very slow lookup. This line of code will run N + 1 queries. The first SQL query will be to retrieve a list of all users and then execute N SQL queries to retrieve the posts for each user.

The includes method allows you to specify relationships to be included in the resulting set of data. This is often called eager loading and improves performance because it allows you to retrieve all the data you need in a single query, without firing additional queries.

users_with_posts = User.includes(:posts)

Dynamic Finders in Rails

Ruby on Rails makes it easy to find a specific record in a table based off some fields. With Active Record you can search a model easily by the following:

User.find_by(first_name: 'Sunny', last_name: 'Mistry')

A cool feature that Rails provides is dynamically generating finder methods for every field on a table.

User.find_by_first_name('Sunny')

An even crazier thing is you can do this for multiple fields!

User.find_by_first_name_and_last_name('Sunny', 'Mistry')

This can go on for as many attributes as you like. I’m not really sure why anyone would do this but it is interesting.

Dynamic Finders Rails Guides

Source Code and Implementation