Search code examples
ruby-on-railseager-loading

Rails includes causing incorrect result


I am using includes to do eager loading on my one query. I am trying to query invoices to get the total amount invoiced. I get 2 different results when I use includes vs. when I don't. Can anyone explain why this is happening/how to best fix this?

all_invoices = Invoice.includes(:contractor, :invoice_items, :refunds).with_user(1).date_between(date_range).search_contractor("tester").displayed_invoices.order(created_at: 'DESC')

tester = Invoice.with_user(1).date_between(date_range).search_contractor("tester").displayed_invoices.order(created_at: 'DESC')

all_invoices.pluck(:total_in_cents).sum  #this will return 80000

tester.pluck(:total_in_cents).sum #this will return 40000

The 2nd one is the correct result of what I"m looking for, but obviously having includes in there is helpful for speed so I'm not trying to remove it, but I need to get the correct result from it.

Anyone have any idea why this is happening?


Solution

  • You are plucking :total_in_cents from two different arrays.

    Tester is plucking from SELECTED from "invoices"

    all_invoices is plucking from SELECTED from "invoices", but also :contractor, :invoice_items and :refunds that meet the same criteria as:

    .with_user(1).date_between(date_range).search_contractor("tester")

    I assume some of these are fillers, but that .with_user queries a user, and that user probably has some other records related in :contractor, :invoice_items or refunds

    You could test it by adjusting the column record names, and re-seeding the database or better yet filtering out those records not associated with the 'Invoices'and running the same query