Pagination with HABTM relationship

I am wondering how to do pagination on a model that has a HABTM relationship through a join model.

The models

Is this impossible or just not challenging enough to get a responce? Please enlighten me if you know how to do this.

Thanks in advance -- K


Here are 2 links to plug-ins that others have recommended. I tried the first one about a month ago and never quite got it working (I can't remember what the problem was).


Is the "Custom Pagination" section here helpful?



The cardboardrocket paginating_find works great for me. Although I had to make some small changes to get it to work properly... here's an example from my code:

@products = Product.find(:all,           :conditions => [ "category_id = ?", params[:id]],           :order => "name",           :page => {:size => 20,                          :first => 1,                          :current => params[:page] || 1 })

Notice the way I handle the :current. anyways hope it helps if you go that route.

good luck, Chad

Chad - that sounds good. Would you mind sharing a code snippet from your view as to how you handle the paging? I think that may have been what I was missing.

Thanks, Paul

Thank you Ryan! The custom pagination worked perfectly.

Here is the code I added to the list method in the controller:

# step 1: read and set the variables you'll need        page = (params[:page] ||= 1).to_i        items_per_page = 8        offset = (page - 1) * items_per_page    # step 2: do your custom find without doing any kind of limits or offsets        @pages = @user.pages    # step 3: create a Paginator, the second variable has to be the number of ALL items on all pages        @which_pages =, @pages.length, items_per_page, page)    # step 4: only send a subset of @pages to the view     @pages = @pages[offset..(offset + items_per_page - 1)]

Mind you, this is not a super efficient method, but as long as the number of user.pages is not too large it should not impact performance. Now if users have thousands of pages ...