sql - How can I efficiently order eager loaded records? -


i have model playlist, , model user, both of have_many of each other, through join model playlistuser.

on playlists#show action, want print list of of playlist's users, along first 2 playlists (ordered :song_count) associated each of users. make 1 query, eager loaded playlist table along users.

right here's have:

playlists/show.html.erb

<% @playlist = playlist.find(params[:id]) %> <% @playlist_users = @playlist.users.includes(:playlists) <% @playlist_users.each |user| %>   <%= user.name %>   <%= user.playlists.order(:song_count).reverse.first.name %>   <%= user.playlists.order(:song_count).reverse.second.name %> <% end %> 

models

class user < activerecord::base   has_many :playlist_users   has_many :playlists, :through => :playlist_users end  class playlistuser < activerecord::base   belongs_to :playlist   belongs_to :user end  class playlist < activerecord::base   has_many :playlist_users   has_many :users, :through => :playlist_users end 

when remove ordering, query extremely fast. ordering, it's slow, because database apparently has query each playlist before can order them.

can order playlists in original query?

actually when do:

user.playlists.order(:song_count).reverse 

you dont leverage eagerload, redo queries each time.

thanks eagerloading have collection in memory, can sort using ruby method sort:

user.playlists.sort_by {|pl| -pl.song_count } 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -