Basil
Basil

Reputation: 13

How to fetch list of objects that doesn't follow has_one association?

File: User.rb

has_one: bike

File: Bike.rb

belongs_to: user

This is the relationship that I have in my Bike and User models. My DB already contains data with a bunch of bikes and users.

How can I pluck data using SQL or active record query that doesn't follow the above associations(has_one)?

So, all I want is the list of Users which has multiple Bikes.

Upvotes: 0

Views: 31

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

You can find users who has more than 1 bike associated with the following query

User.joins(:bike).group('users.id').having('count(bikes.user_id) > 1')

Basically, we are searching for rows in bikes table which have same user_id more than once

Upvotes: 1

Related Questions