Reputation: 359
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?
Upvotes: 0
Views: 46
Reputation: 3175
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)
Upvotes: 1
Reputation: 23661
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
Upvotes: 1