我试图在子集合中获得一组有限的结果
基本上我有这个:
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
这不起作用,我的问题是如何限制每个播放列表最多返回4个曲目
我想要的是响应包含其中最多有4个曲目的所有播放列表(同样应该优化对mongo的查询)
谢谢!
答案 0 :(得分:0)
我得到了解决方案,mongoid创建了一个带有id(track_ids)的数组,其中包含列表中所有轨道的id。
通过覆盖track_ids而不是轨道,不会在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
答案 1 :(得分:0)
我认为以下代码可以解决问题。
user = Model::User.find(token)
playlists = user.playlists[0..3]
decorator = Decorator::PlaylistCollection.new(playlist)
response_with decorator