为什么此AR总和返回预期结果的两倍



我从AR查询中获得了一个奇怪的结果。使用sum给出的结果是预期结果的两倍。

一些背景

@parent.children.size
=> 1
@parent.children
=> [#<Child id: 1, date: "2016-01-01", quantity: 2>]
@parent.children.group_by_month_of_year(:date).count #using groupdate gem
=> {1=>1, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0, 8=>0, 9=>0, 10=>0, 11=>0, 12=>0}

为什么此总和返回1 => 4

@parent.children.group_by_month_of_year(:date).sum(:quantity)
=> {1=>4, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0, 8=>0, 9=>0, 10=>0, 11=>0, 12=>0}

只有1个孩子记录的quantity和2的记录,查询应该返回1 => 2应该不是吗?

我将如何调试?

编辑

查询生成以下SQL

SELECT DISTINCT SUM("purchases"."quantity") AS sum_quantity, 
EXTRACT(MONTH from date::timestamptz AT TIME ZONE 'Etc/UTC' - INTERVAL '0 second')::integer 
AS extract_month_from_date_timestamptz_at_time_zone_etc_utc_interv 
FROM "purchases" 
INNER JOIN "people" ON "purchases"."person_id" = "people"."id" 
INNER JOIN "events" ON "people"."id" = "events"."person_id" 
WHERE "events"."location_id" = $1 AND (date IS NOT NULL) 
GROUP BY EXTRACT(MONTH from date::timestamptz AT TIME ZONE 'Etc/UTC'  INTERVAL '0 second')::integer  
[["location_id", 1]]

与以下关系

class Location
  has_many :events
  has_many :people, -> { distinct }, through: :events
  has_many :purchases, -> { distinct }, through: :people
end
class Event
  belongs_to :location
  belongs_to :person
end
class Person
  has_many :events
  has_many :purchases
end
class Purchase
  belongs_to :person
end

编辑2

更改了如何定义关系(如下),总和是计算正确的结果。

class Location  
  has_many :events
  has_many :people, -> { distinct }, through: :events
  def purchases
    Purchase.where( person_id: self.people.pluck(:id)
  end 
end

在以这种方式汇总时,在关联中使用不同的相关性无效。如果位置和购买之间有多个联接路径,则将不同的局限性应用于最终的汇总结果,而不是基础未聚集的结果集。

我不确定数据模型是否有效。如果您试图通过人和活动获得每个位置的销售,那么您如何知道购买与特定事件以及特定位置有关?

您不需要直接通过将" event_id"添加到购买中,或者通过在您与购买时间相比的事件上有一个时间范围来直接将购买链接到人和事件?<<<<<<<</p>

编辑:

在更好地理解您要做的事情的背景下,这么做...

Purchase.where(person: Person.joins(:events).where(events: {location_id: @location.id}).uniq).
         group_by_month_of_year(:date).sum(:quantity)

最新更新