使用时joins返回的记录可以是重复的。所以如果Tree有很多leaves,那么Tree.joins(:leaves).count将等于叶子的数量,并且有很多重复的 a 记录tree。这是因为joins调用 sqlINNER JOIN会返回两个表的交集。
从Rails 指南:
Category.joins(:posts)
或者,用英语:“为所有包含帖子的类别返回一个类别对象”。请注意,如果多个帖子具有相同的类别,您将看到重复的类别。如果你想要唯一的类别,你可以使用 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")
我更喜欢Railsgroup中的select语句在与其他范围链接时有时会被忽略。
PS:如果您的查询没有任何条件,请invoices尝试使用includes而不是joins. 这将使eagerload所有发票都具有一个查询,而不是对每个发票进行单独的查询shipment。