简体   繁体   中英

How to find records that have the same range of number of children ( Active Record )

I have Area model, User model look like this:

Area model:

Nothing!!!

User model:

belongs_to :area, foreign_key: :area_id

Now, I can get a number of users of one area by Area.find(1).users

But how can I get all areas that have 1 to 10 users, or all areas that have 20 to 30 users?

You can make use of having clause to achieve that

Area.joins(:users).group('users.area_id, areas.id').having("COUNT(users.id) BETWEEN 1 and 10")

This will generate

SELECT "areas".* 
FROM "areas" 
INNER JOIN "users" ON "users"."area_id" = "areas"."id" 
GROUP BY users.area_id, areas.id 
HAVING count(users.id) between 2 and 10

The above code will return the Area records where the associated users range between 1 to 10

NOTE: You can change the range according to your requirements

Make use of rails counter_cache option

class User < ActiveRecord::Base
  belongs_to :area, foreign_key: :area_id, counter_cache: true
end

Now create a migration to for area table

create :areas do |t|
  t.integer :users_count
  ---- Your other fields---
end

Now whenever you associate/remove a user with area object, rails will itself increase or descrease users_count and store it in area object automatically.

You query will be as simple as the following query.

Area.where(users_count: 1..10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM