postgresql - Rails scope where having groupby count -


i have model 'user' can have multiple 'rides' (has_many :rides). ride's table looks this:

# table name: rides # #  id                       :integer          not null, primary key #  user_id                  :integer #  title                    :text #  description              :text 

i want create scope in ride model called 'is_multiple_ride' returns rides have user owns multiple rides. query pretty opposite of distinct(:user_id)

the scope have created looks this:

scope :multiple_live_listings, -> {    where(user_id: ride.group(:user_id).having("count(user_id) > 1").pluck(:user_id)) } 

this scope works it's inefficient when used multiple chained scopes because querying entire ride table rides(in order pluck ids , use them in scope query) rather checking rides in current query.

if there more efficient way please out! using postgresql 9.3.5 , rails 3.2.2, cheers!

given user has 3 rides, if want scope return 3 rides, you'll have away rails helpers little bit (example below). if want single ride belonging user multiple rides, muntasim's solution work.

scope :multiple_live_listings, -> {   where('rides.user_id in (select user_id rides group user_id having count(user_id) > 1)') } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -