Rails 7.0 brings a lot of improvements to the table.
First off, Rails 7.0 is now compatible with Ruby 2.6+. This means that you can use all of your favorite new features from Ruby 2.6 without having to keep up with the latest version of Rails (which has traditionally been difficult).
In addition, 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.
The difference is that associated checks for the presence of the association, while missing checks for the absence of an object.
Take a look at what it was before:
1
@account.users.joins(:contact).where.not(contact_id: nil)
Here is what it will look like 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.
Hence, you can get back an array of objects that are not associated with other records, but with associated you get back an array of objects that are associated with other records.
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.
Further, this new method can be used by both developers and testers to check whether an object is associated with another one or not. It also allows you to check whether a record exists in the database or not.
Read more on this here