Skip to content

Rails 6 sometimes loads associations twice, causing duplicated results #32

@fimmtiu

Description

@fimmtiu

If multiple records in a collection have the same record set for a belongs_to, which itself has a has_many association, the has_many association will return duplicate records. When using ActiveRecord's preload, there are no duplicate records.

Example:

[1] pry> cp = EmailAddress.jit_preload.to_a.first.contact.phone_numbers
=> [#<PhoneNumber:0x00007fa15315b4f8 id: 1, contact_id: 1, phone: "123">,
    #<PhoneNumber:0x00007fa15315b4f8 id: 1, contact_id: 1, phone: "123">]
[2] pry> EmailAddress.preload(contact: :phone_numbers).to_a.first.contact.phone_numbers
=> [#<PhoneNumber:0x00007fa1436fe870 id: 1, contact_id: 1, phone: "123">]

This also results in AR making two identical queries for the phone_numbers instead of only one.

Here's a spec which replicates the problem: https://github.com/clio/jit_preloader/pull/31/files. Seems to only happen under Rails 6.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions