简体   繁体   中英

How to convert following query in rails 3 active record query?

I want to find last 20 days latest data from audit table for that I have written following MySQL query:

 SELECT * 
 from   (select * from audits ORDER BY id DESC) as x 
 where  (auditable_type = 'Investment' 
 and    auditable_id =41 
 and    created_at <= '2011-12-01' AND  created_at >= '2011-11-25')  
 group by date(created_at)

I want to convert it to rails 3 active record query, how should I do so I will get same result from both the queries?

I don't think you can get much better than that (without using some gems like meta_where ):

Audits.where(
    'DATE(created_at) <= ? AND DATE(created_at) >= ? 
     AND auditable_type = ? AND auditable_id = ?',
    Date.new(2011, 12, 01), Date.new(2011, 11, 25), 'Investement', 41
).group('DATE(created_at)').order('id DESC')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM