Updated: Preload associations in loaded records
I ported the initializer to Rails 3.
Related cards:
Rails: Preloading associations in loaded records
Sometimes you want to fetch associations for an ActiveRecord that you already loaded, e.g. when it has deeply nested associations.
Edge Rider gives your models a static method preload_associations
. The ...
How to tell ActiveRecord how to preload associations (either JOINs or separate queries)
Remember why preloading associations "randomly" uses joined tables or multiple queries?
If you don't like the cleverness of thi...
Don't forget: Automatically remove join records on has_many :through associations
Bad
# Given the following models
class Image < ActiveRecord::Base
has_many :album_images
has_many :albums, through: :album_images
end
class Album < ActiveRecord::Base
has_many :album_images
has_many :images, through: :album_i...
Why has_many :through associations can return the same record multiple times
An association defined with has_many :through
will return the same record multiple times if multiple join models for the same record exist (a n:m relation). To prevent this, you need to add ->{ uniq }
as second argument to has_many
(below Ra...
Accept nested attributes for a record that is not an association
Note: Instead of using the method in this card, you probably want to use ActiveType's nested attributes which is a much more refined way of doing this.
The attach...
Rails: How to find records with empty associations
Imagine these models and associations:
class Deck < ApplicationRecord
has_many :cards
end
class Card < ApplicationRecord
belongs_to :deck, optional: true
end
Now you want to find all Decks without any Card or all Cards without a...
Unsaved record disappears when assigning to an association
If this happens to you:
user.avatar = Avatar.new
user.avatar # => nil
(where avatar
is a belongs_to
), you probably declared your association incorrectly.
Always do
class User < ActiveRecord::Base
belongs_to :avatar
...
has_one association may silently drop associated record when it is invalid
This is quite an edge case, and appears like a bug in Rails (4.2.6) to me.
Update: This is now documented on Edgeguides Ruby on Rails:
If you set the :va...
Preloaded associations are filtered by conditions on the same table
When you eagerly load an association list using the .include
option, and at the same time have a .where
on an included table, two things happen:
- Rails tries to load all involved records in a huge single query spanning multiple database tab...