开发者

Given a query how to reduce the number of items

I'm trying to do the following in rails 3:

@groups_active = Group.active_groups(current_user)

active_groups is a scope. This query works fine. I then want to do the following:

if @groups_active.count > 9
   @groups_active[0..10]
end

Meaning if there are more than 10 items in the @groups_activ开发者_如何学运维e, take just the TOP 10, which thanks to the scope ordering are the most active.

Suggestions? Thanks


I'm not sure what your problem is. You can limit the number of results from a query with Model.your_scope.limit(10), and if it is a query that doesn't work with a SQL LIMIT then you can use Model.your_scope.first(10). That's an Array#first, which accepts a fixnum argument to be used as expected…


@groups_active = Group.active_groups(current_user).limit(10)

or you could add the .limit(10) part to your scope.

Edited

I would go with one limit(10) request and one count. It could be more effective then retrieving 20, 50, or more records and using only the first 10 of them. But still, it requires testing and benchmarking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜