Active Record methods for associations
06 Jul 2023I learned about a few useful methods that I hadn’t heard of before.
reflect_on_association
This method allows you to check if an association exists, without making a database query.
- Will return
nilif no associated records are found. - Will return an
AggregateReflectionobject if records are found.
class Post < ActiveRecord::Base
has_many :upvotes
end
class Upvote < ActiveRecord::Base
belongs_to :post
end
Post.reflect_on_association(:upvotes)
extract_associated
Useful if you need to get all associated objects from an ActiveRecord::Relation.
Assuming:
class Author < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :author
end
and we want to get all the books from a list of authors…
Normally, my first thought we be to do something like this:
Author.all.includes(:books).map(&:books)
but there is a more readable way to do this with extract_associated.
Author.all.extract_associated(:books)
which actually does something similar, so the benefit is mostly the readability.
missing
Ever need to find records with no associated records?
For example:
class City < ActiveRecord::Base
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :city
end
if I want to find all cities that have no photos, previously, I thought you needed to do something like this:
City.includes(:photos).where(photos: { city_id: nil })
City.where.missing(:photos)
associated
New in Rails 7. Sort of the inverse of missing, but associated checks for the presence of an association.
Finding all the cities that have photos is as simple as:
City.where.associated(:photos)