基于时间框架从表中获取计数的最有效方法?

时间:2011-11-28 06:33:14

标签: ruby-on-rails ruby ruby-on-rails-3.1

我有一个clicks表,用于记录网站上链接的点击次数。

links表中,我想要一个可以通过cron作业更新的字段weekly_clicks

如何在Ruby / ActiveRecord中编写以下伪代码查询?

Select count(clicks) FROM clicks
  WHERE link_id=xxx
  AND created_at within previous 7 days including today

2 个答案:

答案 0 :(得分:4)

Click.where(:link_id => 'xxx').where('created_at >= ?', 1.week.ago).count

答案 1 :(得分:2)

link = Link.new(params)
link.weekly_clicks = Click.where("created_at > ? and link_id = ?", 1.week.ago, xxx).count
link.save