Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't convert nil into Array will_paginate

Hello guys I am having problems with will_paginate in rails 3, I have this in my constroller

@posts = Post.paginate(:all,
  :include => [:author, :categories],
  :conditions=>"status = 'published'", 
  :order=>"blog_posts.created_at DESC",
  :per_page => 1, :page => params[:page])

and <%= will_paginate @posts %> in my view, but I am getting this error can't convert nil into Array constantly.

Can anyone help me ?

Thanks in advance

like image 803
Michael Avatar asked Dec 12 '10 20:12

Michael


3 Answers

You need to install will_paginate version 3.0.pre2 to have pagination work at the database level rather than on an array.

gem 'will_paginate', '3.0.pre2'
like image 80
Douglas F Shearer Avatar answered Oct 24 '22 02:10

Douglas F Shearer


Try doing this:

@posts = Post.includes(:author, :categories).where(:status => "published").order("blog_posts.created_at DESC").paginate(:per_page => 1, :page => params[:page])

It's the Rails 3 preferred way.

like image 25
iain Avatar answered Oct 24 '22 04:10

iain


iain has already answered this question, but i just wanted to add some data to back up his statement that this command doesn't paginate the entire collection

irb(main):005:0> Benchmark.bm do |x|
irb(main):006:1* x.report {Vote.all.paginate(:per_page => 10, :page => 1)}
irb(main):007:1> x.report {Vote.order("created_at DESC").paginate(:per_page => 10, :page => 1)}
irb(main):008:1> end
      user     system      total        real
210.490000   0.740000 211.230000 (214.754060)
  0.000000   0.000000   0.000000 (  0.429304)

This was run on a database with 500,000 rows in the Vote table (postgres), Rails 3.0.5

So I would agree with him that the scopes are added to the query before execution.

like image 33
Eric Hu Avatar answered Oct 24 '22 04:10

Eric Hu