繁体   English   中英

Rails 3:为什么将具有多个相关记录的重复记录展平?

[英]Rails 3: Why is flatten duplicating records with more than one associated record?

关联:

  • 发货有很多发票
  • 发票属于发货

我得到这样的发货清单...

@shipments = Shipment.joins(:invoices).where(:customer_id => @customer.id).where("customer_open_balance <> 0").where("bill_to IS NULL").order("file_number ASC") 

然后我像这样扁平化...

@invoices = @shipments.map(&:invoices).flatten

我得到重复。 例如,我在此行上方的货件查询@shipments.count获得5条结果。

然后,在我展平后,如果有两张发票的货件被重复,则我得到4张而不是两张@invoices.count我得到7张(应该仍然是5张)。

使用joins ,返回的记录可以重复。 因此,如果Tree leaves很多,则Tree.joins(:leaves).count将等于叶子的数量,并且tree的重复记录很多。 这是因为joins正在调用sql的INNER JOIN ,该INNER JOIN返回两个表的交集。

Rails指南

Category.joins(:帖子)

或者用英语:“为所有带帖子的类别返回类别对象”。 请注意,如果多个帖子具有相同的类别,您将看到重复的类别。 如果需要唯一的类别,则可以使用Category.joins(:post).select(“ distinct(categories.id)”)。

因此,对于您来说,这样的事情会起作用:

@shipments = Shipment.joins(:invoices).where(:customer_id => @customer.id).where("customer_open_balance <> 0").where("bill_to IS NULL").order("file_number ASC").
             select("distinct(shipments.id)")

另一种方法是使用group

@shipments = Shipment.joins(:invoices).where(:customer_id => @customer.id).where("customer_open_balance <> 0").where("bill_to IS NULL").order("file_number ASC").
             group("shipments.id")

我更喜欢group因为与其他作用域链接时,有时会忽略Rails中的select语句。

PS:如果您的查询对invoices没有任何条件,请尝试使用includes而不是joins 这将eagerload所有发票使用一个查询,而不是使每个单独的查询shipment

尝试将.uniq添加到初始查询中:

@shipments = Shipment.uniq.joins(:invoices).where(:customer_id => @customer.id).where("customer_open_balance <> 0").where("bill_to IS NULL").order("file_number ASC")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM