Home > OS >  Rails two scopes on has many through returns a bigger count than one single scope
Rails two scopes on has many through returns a bigger count than one single scope

Time:09-24

There's a Customer class with the following associations and scopes:

 has_many :hangouts
 has_many :bookings, through: :hangouts
 scope :already_finished, -> { joins(:bookings).where("bookings.time < ?", DateTime.now) }
 scope :who_booked_trips, -> { where(won_deal: true) }

When I run

Customer.who_booked_trips.count 

I get the number 653

When I run

Customer.already_finished.count 

I get the number 662

When I run

Customer.who_booked_trips.already_finished.count

I get the number 661!

Should not the who_booked_trips.already_finished.count be smaller than who_booked_trips.count ?

What am I missing here?

Thanks

CodePudding user response:

Using joins will result in duplicate customers being returned. Take this simple example where you have 1 customer who has 2 bookings:

> Customer.count
=> 1
> Customer.joins(:bookings).count
=> 2
> Customer.joins(:bookings).distinct.count
=> 1

If you only want to return unique customers, call the distinct method on the scope:

 scope :already_finished, -> { joins(:bookings).where("bookings.time < ?", DateTime.now).distinct }

CodePudding user response:

Append .uniq

scope :already_finished, -> { joins(:bookings).where("bookings.time < ?", DateTime.now).uniq }

That should return all uniq records.

  • Related