Getting the last document of the limited result of a Mongoid and .count () request

I am using Mongoid to work with MongoDB. Everything is in order, I really like it and so on. In my blog application (message manager, index action) I have this code:

@posts = Post.without(:comments)
@posts = @posts.my_search(params[:s]) if params[:s]
@posts = @posts.order_by([:created_at, :desc])
@posts = @posts.where(:pid.lt => params[:p].to_i+1) if params[:p]
@posts = @posts.limit(items_per_page+1)

The “where” part is the implementation of my own pagination method (it allows me to output the results in only one direction, but without skip(), which I consider a plus). Now there are a few small problems that make me feel uncomfortable:

For my pagination, I need to get the last message in this limit. But when I do @posts.last, I get the last document of the entire request without restrictions. Well, this is strange, but not a big problem. In addition, the query results act like an almost-ordinary array, so at this moment I get the last element with @posts.pop(funny, but it doesn’t delete any documents) or@posts.fetch(-1)

I have a feeling that this is not the “right way”, and there is something more elegant. It also @posts.countgenerates the second request in the same way as the first (without limitation), but only with the “score”, and I do not like it.

If the last line looks like

@posts = @posts.limit(items_per_page+1).to_ary

, (), @posts.count , ( ) @posts.size - items_per_page+1 ().

, :

1) "" ?

2) , ?

UPD:

3) @posts.first , , ?

+5
1

:

Post.last 

:

Post.order_by([:created_at, :desc]).last

:

Post.order_by([:created_at, :desc]).count

:

@posts = Post.limit(10).paginate(:page=>pararms[:page])

:

<%= will_paginate @posts %>

- mongoid lazy :

@posts = Post.all #no query has been run yet
@posts.first #Ok, a query has finally been run because you are accessing the objects
+3

All Articles