1

How could you perform a where clause(open to other ways of solving the same problem) with active record that only returns records that have a over 10 associations.

For Example:

I have Orders and Toys. Each order can have many toys, a 1 to many relationship.

I only want orders that have at least 10 toys.

What active record query would return to me only orders that have atleast 10 toys ?

user3738936
  • 936
  • 8
  • 22

1 Answers1

1

This should do the trick:

Order
  .joins(:toys)
  .group('orders.id')
  .having('count(toys.*) > ?', 10)
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • what is your ```.*``` doing ? – user3738936 Apr 01 '19 at 20:23
  • it tells postgresql to count based on all field of the `toys` table. You may think you should just count the `id` column for example, but postgresql has built-in optimization and can detect a `count(some_table.*)` and perform better than doing `count(some_table.id)` – MrYoshiji Apr 01 '19 at 22:55