Paginating with couchrest_model

Hello,

In my rails application, I am using couchrest_model to connect to a
couchDB database.

I have a model like this:

class Author < CouchRest::Model::Base

  property :id, Integer
  property :title, String
  property :first_name, String
  property :last_name, String

  # view to get only the documents which starts with "authors" - Table
Authors
  view_by :id,
          :map => "function(doc) {
            if(doc._id.indexOf('authors') == 0) {
              emit(null, doc);
            }
          }"

end

In the controller the function is simple:


def list
   @authors = Author.by_id()
end

And in the view I iterate the @authors to show the results.

I would like to implement pagination but I don’t know how. I already
implemented pagination before, when I was using a PostgreSQL database
and active records (will_paginate), but now, I am stuck with this.

Anyone can help me with a simple example?

There is a recipe for pagination in the couchdb guide

http://guide.couchdb.org/draft/recipes.html#pagination


Oscar Del B.
Sent with Sparrow (http://www.sparrowmailapp.com/?sig)

Hi,

You might might be better posting this couchrest messages to the
couchrest
google group, I only found this message by chance.

Firstly, your map function is not very good; sticking a doc into a the
value field of the index is a really bad idea. Secondly, you should be
using the new design blocks in Couchrest to make things easier to
paginate
using the Kaminari plugin. Thirdly, CouchDB, like MongoDB, uses an id
field
called ‘_id’, you really don’t want to be overwriting id properties if
you
can help it.

Assuming that you have some kind of weird migration going on and you
don’t
want to use the normal ‘type’ property, here’s what I’d recommend:

class Author < CouchRest::Model::Base
  property :title, String
  property :first_name, String
  property :last_name, String

  design do
    view :by_author,
         :map => "function(doc) {
            if (doc['_id'].indexOf('authors') == 0) {
              emit(doc['_id'], 1);
            }
          }", :reduce => "function(k,v,r) { return sum(v); }"
  end
end

# Define view in controller:
@authors = Author.by_author.page(params[:page])

# Paginate it in view (requires kaminari)
paginate @authors

(If you were using the type property, you wouldn’t need to add your map
method and could just use Author.all.page(params[:page]), with the
same
effect.)

You can find more info about this sort of stuff in the couchrest.info
site,
especially the views page 1

Good luck,
sam