shane
shane

Reputation: 89

Rails, find duplicate entries in postgres database

I have the following classes:

class Product < ActiveRecord::Base
  has_one :total_purchase
end

class TotalPurchase < ActiveRecord::Base
  belongs_to :product
end

My tables have the following columns (I've left out the majority for clarity):

Product
id | title | end_date | price | discount

TotalPurchase
id | product_id | amount

Numerous products have the same products.title, products.end_date and totalpurchases.amount and I'd like to identify all of those between certain dates. I'm currently using the following sql query to identify them:

Product.find_by_sql("select products.title, products.end_date, total_purchases.amount from products left join total_purchases on products.id = total_purchases.product_id where products.end_date > '2012-08-26 23:00:00' and productss.end_date < '2012-09-02 22:59:59' group by products.end_date, products.title, total_purchases.amount having count(*) > 1")

How would I write the above as a rails query rather than using find_by_sql?

Upvotes: 0

Views: 1416

Answers (1)

MrTheWalrus
MrTheWalrus

Reputation: 9700

Product.select('products.end_date, products.title, total_purchases.amount').
  joins('left join total_purchases on products.id = total_purchases.product_id').
  where('products.end_date > :start_date 
    and products.end_date < :end_date',
    :start_date => '2012-08-26 23:00:00', 
    :end_date => '2012-09-02 22:59:59').
  group('products.end_date, products.title, total_purchases.amount').
  having('count(*) > 1')

Upvotes: 1

Related Questions