Question

I'm trying to get a limited set of results in a sub collection

Basically I have this:

user = Model::User.find(token)
playlists = user.playlists
playlists.each do |playlist|
  criteria = playlist.tracks.limit(4)    #I Want to limit these to return max 4 tracks
  #the criteria is perfect here but the decorator still returns all the tracks
  #setting this criteria on the user saves the new tracks list limited by 4
  #like this:
  playlists[index].tracks = criteria
end

decorator = Decorator::PlaylistCollection.new(playlist)
response_with decorator

This isn't working, and my question is how can I limit every playlist to return 4 tracks max

What I want is that the response contains all the playlists with 4 tracks max in it (also the queries on mongo should be optimized)

  • display all the playlist
  • every playlist contains max 4 tracks
  • it's required to prevent the call for all the tracks of the playlist from mongoid/mongo

Thanks!

Was it helpful?

Solution

I got the solution, mongoid creates an array with ids (track_ids) with all the ids of the tracks in the list.

By overriding the track_ids instead of tracks nothing is queried or stored in mongoid.

user = Model::User.find(token)
playlists = user.playlists
playlists.map do |playlist|
  playlist.track_ids = playlist.track_ids.take(4)
end

decorator = Decorator::PlaylistCollection.new(playlist)
response_with decorator

OTHER TIPS

I think that the following code would do the trick.

user = Model::User.find(token)
playlists = user.playlists[0..3]
decorator = Decorator::PlaylistCollection.new(playlist)
response_with decorator
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top