I am using Rails 4.2 with PostgreSQL. I have a Product
model and a Purchase
model with Product
has many
Purchases
. I want to find the distinct recently purchased products. Initially I tried:
Product.joins(:purchases)
.select("DISTINCT products.*, purchases.updated_at") #postgresql requires order column in select
.order("purchases.updated_at DESC")
This however results in duplicates because it tries to find all tuples where the pair (product.id
and purchases.updated_at
) has a unique value. However I just want to select the products with distinct id
after the join. If a product id appears multiple times in the join, only select the first one. So I also tried:
Product.joins(:purchases)
.select("DISTINCT ON (product.id) purchases.updated_at, products.*")
.order("product.id, purchases.updated_at") #postgres requires that DISTINCT ON must match the leftmost order by clause
This doesn't work because I need to specify product.id
in the order
clause because of this constraint which outputs unexpected order.
What is the rails way to achieve this?
rails
way of doing this? – Westmoreland