Rails 3 query on condition of an association's count

后端 未结 3 2063
清歌不尽
清歌不尽 2020-12-02 15:42

In Rails 3 with mysql, suppose I have two models, Customers and Purchases, obviously purchase belongs_to customer. I want to find all the customers with 2 orders or more. I

3条回答
  •  佛祖请我去吃肉
    2020-12-02 16:25

    No need to install a gem to get this to work (though metawhere is cool)

    Customer.joins(:purchases).group("customers.id").having("count(purchases.id) > ?",0)
    

提交回复
热议问题