Undefined method `paginate'

淺唱寂寞╮ 提交于 2019-12-10 03:28:56

问题


I'm trying to use the will_paginate gem but something's wrong. I'm stuck with an undefined method `paginate' error. I read many issues and try a lot of things. Here's what I've got :

This is my LocationsController.rb:

def index
  @locations = Location.all    
  respond_to do |format|
    @locations = @locations.paginate(:page => params[:page], :per_page => 10) 
    format.html  #index.html.erb
    format.json { render json: @locations }
  end 
end

And this is my will_paginate's line in my index.html.erb:

<%= will_paginate @locations %>

And this is the error:

undefined method `paginate' for #<Class:0xaa2e48c>

I also add the require part in my Gemfile:

gem "will_paginate", "~> 3.0.4", :require => nil

And this at the end of my environment.rb:

require "will_paginate"`

回答1:


will_paginate doesn't work like that. paginate is a method of the Location class:

def index
  @locations = Location.paginate(page: params[:page], per_page: 10) 
  respond_to do |format|
    format.html
    format.json { render json: @locations }
  end 
end

Moreover, to use will_paginate you should just need to add the line below in your Gemfile, no modification in environment.rb is required:

gem "will_paginate", "~> 3.0.4" 



回答2:


Make sure to restart the server after installing the 'will_paginate' gem.

This was the stupid issue in my case.




回答3:


You try to paginate array. Try this:

def index
   @locations = Location.paginate(:page => params[:page], :per_page => 10)   

     respond_to do |format|
      format.html  #index.html.erb
      format.json { render json: @locations }
    end 
  end

If you want to paginate array see Paginating an Array in Ruby with will_paginate



来源:https://stackoverflow.com/questions/17105715/undefined-method-paginate

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