[英]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.