I have a table of Groups that have a “capacity” column and has a has_many relationship with Enrollments. I want to be able to find Groups whose count of enrollments is less than it’s capacity, so using ActiveRecord + Ruby I can do this:
Group.all.select {|g| g.enrollments.count < g.capacity }.first
But it seems like there should be a way to do this in SQL, I just don’t know how. Any ideas?
The pure SQL way of doing this would be
Or in activerecord
A counter cache with an index on the counter column will be faster though, although obviously you have to not create enrollments behind acriverecord’s back.