我有以下课程:
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.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?
答案 0 :(得分: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')