Caution: `.includes` can make `.ids` non-unique.

This can happen with a very simple model:

class Note
  has_many :attachments
end

Everything looks normal:

Note.all.to_a.size # => 8
Note.all.ids.size # => 8

Then .includes leads to weird results:

Note.all.includes(:attachments).to_a.size # => 8
Note.all.includes(:attachments).ids.size # => 12

If a note has 5 attachments, its id will be included 5 times.

With .preload it works as expected:

Note.all.preload(:attachments).to_a.size # => 8
Note.all.preload(:attachments).ids.size # => 8

Note

I created a bug report for this in the Rails project:
https://github.com/rails/rails/issues/46455 Show archive.org snapshot

Klaus Weidinger Over 1 year ago