← Back to Upcase

One-to-Many query within AR


(Iurii Plugatariov) #1

He there! Today I’ve stucked with kinda trivial problem, I forgot almost everything about quering with Active Record and can’t find how to solve it without generating raw sql query. Let’s imagine we have User model which belongs_to Organization(obviously that this model has_many :users) I need to generate an AR query where I can get organization which has 10 or more users. Any ideas?


(Iurii Plugatariov) #2

One of the variants how I got the correct answer, but it seems to me not ok

Organization.joins(:users).group(:organization_id).having('COUNT(organization_id) > 10').first

(Curt) #3

I’m new to this, and am interested in the answer. Should it be counting organization_id or the users ids for an organization?

Organization.joins(:users).group(“users.organization_id”).having(“count(users.id) > 10”)


(Ben Orenstein) #4

That looks fine to me. I asked in Campfire and another thoughtbotter agreed that your approach is pretty much how he’d do it.