I have a model 'User' that can have multiple 'Rides' (has_many :rides). Ride's table looks like this:
# Table name: rides
#
# id :integer not null, primary key
# user_id :integer
# title :text
# description :text
I want to create a scope in the Ride model called 'is_multiple_ride' which returns rides that have a user which owns multiple rides. The query is pretty much the opposite of distinct(:user_id)
The scope I have created looks like this:
scope :multiple_live_listings, -> {
where(user_id: Ride.group(:user_id).having("COUNT(user_id) > 1").pluck(:user_id))
}
This scope works however it's inefficient when used with multiple chained scopes because it is querying the entire Ride table for rides(in order to pluck the IDs and then use them in the scope query) rather than checking only the rides in the current query.
If there is a more efficient way to do this please help out! I am using PostgreSQL 9.3.5 and Rails 3.2.2, cheers!