Rails 3 query on condition of an association's count

后端 未结 3 2036
清歌不尽
清歌不尽 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.)

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-02 16:33

    This is a bit more verbose, but if you want Customers where count = 0 or a more flexible sql, you would do a LEFT JOIN

    Customer.joins('LEFT JOIN purchases on purchases.customer_id = customers.id').group('customers.id').having('count(purchases.id) = 0').length
    
    0 讨论(0)
提交回复
热议问题