Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will_paginate with named_scopes

I'm using will_paginate for pagination, which has been working well so far, except for this one thing.

If I try to paginate a scope, for instance

class User < ActiveRecord::Base

    named_scope :scope, lambda { etc }

end

User.scope.paginate({:page => params[:page], :per_page => 10})

That will tell me paginate is an undefined method. I'd rather not have to use a second solution for only this scope, is there something I can do here?

like image 567
Lowgain Avatar asked May 07 '10 22:05

Lowgain


3 Answers

Lowgain, klew's version should work out of the box. In your version you should write:

User.scope.paginate :page => params[:page], :per_page => 10

I prefer another approach to pagination. It allows to make controller more clean and encapsulates pagination at model level, for e.g.:

class Property < ActiveRecord::Base
  named_scope :all_properties, lambda {{ :order => "name asc" }}

  def self.admin_properties(page = 1)
    self.all_properties.paginate(:page => page, :per_page => Settings.admin.per_page)
  end
end

And in a controller pretty clear code:

class Admin::PropertiesController < Admin::AdminController
  def index
    @properties = Property.admin_properties(params[:page])
  end
end

p.s: Settings.admin.per_page - this is Searchlogic settings.

like image 139
Voldy Avatar answered Nov 13 '22 06:11

Voldy


I have a named_scope defined like this:

 named_scope :look_for, lambda { |search| bla;bla;bla }

I call it:

 Person.look_for(params[:search]).paginate :page => params[:page]

And it works. Maybe you need some parameter to your scope?

like image 42
klew Avatar answered Nov 13 '22 04:11

klew


Kind of a weird solution, but

User.scope.find(:all).paginate :page => params[:page], :per_page => 10

works?

like image 2
Lowgain Avatar answered Nov 13 '22 04:11

Lowgain