Rails 6.1 adds where.associated to check association presence

Nithin Krishna

By Nithin Krishna

on December 18, 2020

This blog is part of our  Rails 6.1 series.

Rails 6.1 simplifies how to check whether an association exists by adding a new associated method.

Let's see an example of it.

1class Account < ApplicationRecord
2  has_many :users, -> { joins(:contact).where.not(contact_id: nil) }
3end

This will return all users with contacts. If we rephrase that sentence then we can say that "this will return all users who are associated with contacts".

Let's see how we can do the same with the new associated method.

1class Account < ApplicationRecord
2  has_many :users, -> { where.associated(:contact) }
3end

Now we can see that the usage of associated decreases some of the syntactic noise we saw in the first example. This method is essentially a syntactic sugar over the inner_joins(:contact).

Check out the pull request for more details.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.