user2320239 user2320239 - 1 month ago 6
Ruby Question

Finding the number of models with a certain attribute

Hi I have a model in my database User, a user can have zero, one or many Cars. I want to find all the Users in my database with one or more Cars. At the moment I have logic that says:

@car_user_count
for user in Users.all do

if user.cars.count > 0
@car_user_count = @car_user_count + 1

end


This seems like an overly complicated way of doing this. I assume there must be a way of doing something like:

User.where(Cars.count > 0).all.count


but I just can't seem to get it to work, any help with this would be greatly appreciated.

Answer

I want to find all the Users in my database with one or more Cars.

User.includes(:cars).where.not(cars: { id: nil })
Comments