Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kaminari undefined method `total_pages'

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.

like image 282
dongdongxiao Avatar asked Mar 17 '16 20:03

dongdongxiao


1 Answers

You need to paginate both queries. I recommend 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.

like image 120
Shelvacu Avatar answered Oct 22 '22 23:10

Shelvacu