Menu

Toshimaru's Blog

Build group_by and having query with ActiveRecord

Want to build query which has group by and having(like below) with ActiveRecord?

SELECT bar, count(*)  
FROM tables
GROUP BY foo, bar
HAVING count(*) > 1;

You can build it by using group and having which are ActiveRecord::QueryMethods.

ActiveRecordModel.group(:foo, :bar).having("count(*) > 1").count

See also

Load more