Ruby/Rails - kaminari undefined method pagination errors

落花浮王杯 提交于 2019-12-21 05:44:22

问题


I'm not sure what I did, but kaminari has started acting weird in my app.

In my controller:

@producers = Producer.order(:name).page(params[:page])

view:

<%= paginate @producers %>

results in:

undefined method `num_pages' for #<ActiveRecord::Relation:0x000001026e6308>

If I add .per in my controller:

@producers = Producer.order(:name).page(params[:page]).per(25)

I get

undefined local variable or method `per' for #<ActiveRecord::Relation:0x0000010928ef60>

Finally, strangely, if I move my .order(:name) to the end, it works:

@producers = Producer.page(params[:page]).order(:name)

I'm guessing some other gem I have installed has a page scope or method that's causing problems?

Thanks.


回答1:


Well, just figured it out. I had Active Admin installed. It installed will_paginate as a dependency.

In the latest commits for Active Admin, will_paginate has been replaced with kaminari.

I changed my Gemfile to pull Active Admin from github. will_paginate was removed from my bundle and now everything works. You can do this by putting the following line into your gemfile:

gem "activeadmin", git: "https://github.com/gregbell/active_admin"



回答2:


I had the same problem with another gem that required will_paginate. The issue was resolved with this code snippet which was taken from active_admin wiki page:

if defined?(WillPaginate)
  module WillPaginate
    module ActiveRecord
      module RelationMethods
        def per(value = nil) per_page(value) end
        def total_count() count end
      end
    end
    module CollectionMethods
      alias_method :num_pages, :total_pages
    end
  end
end

Put it in an initializer.




回答3:


To solve the problem, include gem 'kaminari' and remove will_paginate. Since I have already been using will_paginate, I just updated my current will_paginate calls to kaminari. They are very similar to implement and easy enough to change.




回答4:


I tried johnnycakes's solution, but it kept giving me stack level too deep errors on the dashboard (similar to https://github.com/gregbell/active_admin/issues/157)

The solution I found was to specify this revision:

gem 'activeadmin', :git => 'git://github.com/gregbell/active_admin.git', :ref => '811f286fda3b6dfa91aa'


来源:https://stackoverflow.com/questions/6919082/ruby-rails-kaminari-undefined-method-pagination-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!