Rails:可以重写此SQL查询以使用ActiveRecord吗?

时间:2011-06-09 22:07:22

标签: sql ruby-on-rails activerecord

查询工作正常,但作为练习,我如何使用ActiveRecord方法转换它?

Model.find_by_sql("SELECT *, SUM(impressions) AS impressions, SUM(cost) AS cost
                   FROM display_stats
                   WHERE (created_at >= '#{(Date.today-2).to_time.strftime('%Y-%m-%d')}'
                          AND created_at <= '#{(Date.today-1).to_time.strftime('%Y-%m-%d')}')
                   GROUP BY banner_id
                   ORDER BY cost DESC")

这是我的模型结构:

DisplayStat (id: integer,
             banner_id: integer,
             comments: string,
             impressions: integer,
             cost: integer,
             created_at: datetime,
             updated_at: datetime)

是否可以在不使用原始SQL的情况下编写上述查询?


运行Rails 3.1和MySQL 5.5

1 个答案:

答案 0 :(得分:2)

试试这个:

DisplayStat.
  select("banner_id, SUM(impressions) AS impressions, SUM(cost) AS cost").
  where(:created_at => (2.days.ago.beginning_of_day..2.days.ago.end_of_day)).
  group(:banner_id).
  order("cost DESC")

日期范围从一天的开始到结束; 2天前。将日期范围传递给条件哈希时,rails会生成BETWEEN运算符。