0

我有以下课程:

class Product < ActiveRecord::Base
  has_one :total_purchase
end

class TotalPurchase < ActiveRecord::Base
  belongs_to :product
end

我的表格有以下列(为了清楚起见,我省略了大部分):

Product
id | title | end_date | price | discount

TotalPurchase
id | product_id | amount

许多产品具有相同的 products.title、products.end_date 和 totalpurchases.amount,我想找出特定日期之间的所有产品。我目前正在使用以下 sql 查询来识别它们:

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")

我如何将以上内容编写为 rails 查询而不是使用 find_by_sql?

4

1 回答 1

1
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')
于 2012-09-05T11:08:39.283 回答