kaminari undefined method `total_pages'

我只是一个虾纸丫 提交于 2019-12-23 07:39:09

问题


While using kaminari, I got an error.

Gemfile:

# gem 'will_paginate', '~> 3.0.6'
# gem 'will_paginate-bootstrap'

gem 'kaminari'

lists_controller.rb

  def index
    if params[:tag]
      @lists = List.tagged_with(params[:tag]).order(created_at: :desc).paginate(page:params[:page], per_page: 3 )
    else
      @lists = List.all.order(created_at: :desc)
    end
  end

I also user .page params[:page].per(2) follow .order(created_at: :desc) but not work

views/lists/index.html.erb

<%= paginate @lists %>

the error is here

undefined method `total_pages' for #<List::ActiveRecord_Relation:0x007fa2303e3fa8>
Extracted source (around line #26):             
    </div>
  </div>
<%= paginate @lists %>
  <div class="container"> 
    <div class="row">
      <div class="col-md-8">

I was following a railscasts video about kaminari, but they did not have any error.


回答1:


You need to paginate both queries. I reccomend something like:

def index
  if params[:tag]
    @lists = List.tagged_with(params[:tag])
  else
    @lists = List.all
  end
  @lists = @lists.order(created_at: :desc).paginate(page:params[:page], per_page: 3 )
end

Otherwise @lists will not be a pagination object when params[:tag] is nil.




回答2:


Try to paginate with:

 List.tagged_with(params[:tag]).order(created_at: :desc).page(params[:page]).per(3)



回答3:


I had a similar issue, it was because the commontator gem was bringing in methods from will_paginate and overriding the base ActiveRecord class.

The error was in the call stack for the page_entries_info method which seems to be a common method name between both libraries.

To fix, you can explicitly reference the method with this:

So the view code:

      <%= Kaminari::Helpers::HelperMethods.page_entries_info @events %>
      <%= link_to "Next", path_to_next_page(@events) %>
      <%= link_to "Prev", path_to_prev_page(@events) %>

and in an initializer (initializers/kaminari_config.rb)

module Kaminari
  module Helpers
    module HelperMethods
      extend ActionView::Helpers::TranslationHelper
      module_function :page_entries_info
    end
  end
end

This is a very hacky fix, but hope it helps.




回答4:


Try:

order(:nome).page page

Worked for me



来源:https://stackoverflow.com/questions/36070991/kaminari-undefined-method-total-pages

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