Dave Hill
Dave Hill

Reputation: 31

Kaminari not applying pagination methods to models defined within gems

I am using Mongoid with Kaminari for pagination and it is working fine for models defined within the Rails application itself. However, I am also including a gem which defines several more models, and when I try to use pagination on those models, the 'page' method is undefined. It is as though Kaminari doesn't find those models when initializing.

I've tried reordering the initialization process as well as create an initializer that specifically tries to add the scope and Kaminari routines to the Gem models:

GemModel.class_eval do 
  include Kaminari::ConfigurationMethods 

  scope :page, Proc.new {|num|
    limit(default_per_page).offset(default_per_page * ([num.to_i, 1].max - 1))
  } do 
    include Kaminari::ActiveRecordRelationMethods 
    include Kaminari::PageScopeMethods 
  end
end 

However, this creates an undefined method 'conditions' for nil:NilClass from (eval):3:in 'page'.

Is there any way to get Kaminari to work with models defined in gems?

Upvotes: 1

Views: 743

Answers (1)

Dave Hill
Dave Hill

Reputation: 31

You need to tell Kaminari specifically about the models within a gem if you want to paginate those models. You can do that by adding the following code to your config/environment.rb file or as a separate initializer (e.g. initializers/kaminari.rb).

GemModel.send(:include, Kaminari::MongoidExtension::Document)

Another thing that tripped me up is that GemModel cannot be a superclass of anything. Otherwise, you will get nil object errors.

Upvotes: 2

Related Questions