Activerecord获得多个最近的记录

时间:2011-08-19 07:24:49

标签: ruby-on-rails ruby activerecord

我有以下简化表:

| id | order_id | created_at |  
| 1  |  1       | 2011-07-11 |  
| 2  |  1       | 2011-07-12 |  
| 3  |  2       | 2011-07-13 |  
| 4  |  2       | 2011-07-14 | 

现在我正在尝试获取订单列表的所有记录,但每个order_id只有最新的记录

EdpuOrder.find(:all, :conditions => "edpu_orders.order_id IN (#{ids})", :order => "edpu_orders.created_at")

ids变量由子查询生成,现在说它是“1,2”。上面的陈述应该返回记录2和4.任何想法?

3 个答案:

答案 0 :(得分:0)

找到一种将ID放入数组的方法。

ids = [1, 2]
EdpuOrder.where(:order_id => ids).order(:created_at)

顺便说一下,这只适用于Rails 3及以上版本。

答案 1 :(得分:0)

尝试此范围(我用适当的表名替换your_table):

named_scope :top_orders, :from=>"(select * from your_table order by created_at desc) as tmp", :group => "order_id"

现在YourModel.top_orders应该做的事情

答案 2 :(得分:0)

EdpuOrder.where("(edpu_orders.order_id, edpu_orders.id) IN 
         (SELECT order_id, MAX(id) FROM edpu_orders GROUP BY order_id)").
order("created_at DESC")