Rails 7.0 adds association checking with the associated method

Rails 7 has added a query method associated which checks for the presence/absence of an association. This is very useful instead of joining and checking whether an id exists.

Before

1
@account.users.joins(:contact).where.not(contact_id: nil)

After

1
@account.users.where.associated(:contact)

The method associated exists in the ActiveRecord::QueryMethods::WhereChain class. The method returns a relation with inner join and where clauses to check for the presence of the association in question.

Additionally, we can also pass multiple relation names to the method as shown below.

1
@account.users.where.associated(:contact, :next_of_kin)

The above query would only return a valid relation if both conditions that have been provided are met. In the case that either one or both are not met then it would result in an empty relation being returned.

Read more on this here