Rails 3 query on condition of an association's count

后端 未结 3 2058
清歌不尽
清歌不尽 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:06

    The documentation on this stuff is fairly sparse at this point. I'd look into using Metawhere if you'll be doing any more queries that are similar to this. Using Metawhere, you can do this (or something similar, not sure if the syntax is exactly correct):

    Customer.includes(:purchases).where(:purchases => {:count.gte => 2})
    

    The beauty of this is that MetaWhere still uses ActiveRecord and arel to perform the query, so it works with the 'new' rails 3 way of doing queries.

    Additionally, you probably don't want to call .all on the end as this will cause the query to ping the database. Instead, you want to use lazy loading and not hit the db until you actually require the data (in the view, or some other method that is processing actual data.)

提交回复
热议问题