Rails 两个作用域比一个作用域多 returns

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

有一个客户 class 具有以下关联和范围:

 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) }

当我运行

Customer.who_booked_trips.count 

我得到号码 653

当我运行

Customer.already_finished.count 

我得到号码 662

当我运行

Customer.who_booked_trips.already_finished.count

我得到号码 661!

who_booked_trips.already_finished.count 不应该小于 who_booked_trips.count 吗?

我在这里错过了什么?

谢谢

使用 joins 将导致重复的客户被 returned。以这个简单的例子为例,您有 1 位客户有 2 次预订:

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

如果您只想 return 个唯一客户,请在范围上调用 distinct 方法:

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

附加.uniq

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

那应该 return 所有 uniq 记录。