Over a million developers have joined DZone.

Mongoid 2.0.2 Dropped Pagination - Kaminari

· Database Zone

To stay on top of the changing nature of the data connectivity world and to help enterprises navigate these changes, download this whitepaper from Progress Data Direct that explores the results of the 2016 Data Connectivity Outlook survey.

I was a bit surprised to see mongoid drop pagination support in 2.0.2 (here and here) this summer. It got some people confused (see #983). In a project that uses will_paginate, this results in very slow large queries, but no other breakage. It looks like Mongoid did the right thing though – their implementation was messy and other extensions do a much cleaner job.

Here’s what I had to do to switch from will_paginate to kaminari. The latter works well with Mongoid 2.0.2.

Replace will_paginate with kaminari in Gemfile.

  1. gem "kaminari", "0.12.4"

Replace all calls to .paginate :page => params[:page], :per_page => 20 with the kaminari methods.

  1. Model.desc(:created_at).page(params[:page]).per(20)

There may be some loading order issues since kaminari injects methods on load. For delayed jobs I had to do the following in the initializer (see #10).

  1. Delayed::Job.send(:include, Kaminari::MongoidExtension::Document)

If you have a shared pagination block (eg. app/views/shared/pagination/_pagination.html.haml) change it to use kaminari layouts.

  1. #pagination
  2. = paginate items

There’s a pull request #140 for page_entries_info, it looks like it still has a couple of issues. We’ve added config/initializers/kaminari.rb for now.

If you’re paginating arrays you can inject a few methods into a paged result set on-the-fly to make it play nice.

  1. @paged_result_set.instance_eval <<-EVAL
  2.   def current_page
  3.     #{params[:page] || 1}
  4.   end
  5.   def num_pages
  6.     count
  7.   end
  8.   def limit_value                                                                               
  9.     20
  10.   end
  11. EVAL

Turn Data Into a Powerful Asset, Not an Obstacle with Democratize Your Data, a Progress Data Direct whitepaper that explains how to provide data access for your users anywhere, anytime and from any source.


Published at DZone with permission of Daniel Doubrovkine. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}