Reputation: 13
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
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