undefined method `paginate' for Array on Rails

2019-09-10 18:50发布

问题:

Trying to use will_paginate gem.

My Gem file has:

gem 'will_paginate', '~> 3.0.0'

My orders_controllers.rb:

def index
    @orders = Order.all.paginate(:page => params[:page], :per_page => 20)

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

On my index.html.erb I've put:

<%= will_paginate @orders %>

Error:

NoMethodError in OrdersController#index

undefined method `paginate' for #<Array:0x007f79a1be62f8>
Rails.root: /home/askar/Dropbox/rails_studio/somics

Application Trace | Framework Trace | Full Trace
app/controllers/orders_controller.rb:5:in `index'

I now there's kaminari gem for pagination, but I want to know about will_paginate.

回答1:

Array functions are disabled by default you have to enable them by requiring them in your WillPaginate file:

require 'will_paginate/array'


回答2:

In your config/initializers add will_paginate_array_fix.rb file and in will_paginate_array_fix.rb file add

require 'will_paginate/array'


回答3:

I just wanted to add that after you do as the previous answer suggests:

In your config/initializers add will_paginate_array_fix.rb file and in will_paginate_array_fix.rb file add

require 'will_paginate/array'

You need to restart your server in order for that to take effect.



回答4:

I don't think we need to add any files in the config/initializers. Just after doing all the steps as mentioned on the official github page restart the rails server and all will work fine.