Rails: Showing 10 or 20 or 50 results per page with will_paginate how to?
Asked Answered
I

3

6

me again...

I need show 10 or 20 or 50 results number of results per page with a select options in my list of posts using will_paginate plugin

Can you help me please?

Thanks!

Insupportable answered 15/8, 2009 at 3:40 Comment(0)
P
21

Looks like the OP also asked here: http://railsforum.com/viewtopic.php?id=33793 and got much better answers.

To adapt the best solution there, here's what I like:

(in the view)

<%= select_tag :per_page, options_for_select([10,20,50], params[:per_page].to_i),
       :onchange => "if(this.value){window.location='?per_page='+this.value;}" %>

(in the controller)

@per_page = params[:per_page] || Post.per_page || 20
@posts = Post.paginate( :per_page => @per_page, :page => params[:page])
Predicant answered 16/4, 2010 at 5:57 Comment(1)
Thanks for your example - that was right on what I needed for a Rails 3 project. One tip though... you may want to change the part of your select_tag that says "params[:per_page].to_i" to just "@per_page" since we already know the @per_page from the controller. This change ensures the proper value is selected in your select tag even if there is no per_page param (eg. the index action).Antichlor
S
1

To set a class wide Default

class Post < ActiveRecord::Base

  def self.per_page
    25
  end

end

Or on a query by query basis use the per_page in your call

class Post <ActiveRecord::Base

  def self.posts_by_paginate
    paginate(:all, :per_page => 25, :conditions => ["published = ?", true])
  end

end
Stasiastasis answered 15/8, 2009 at 4:6 Comment(0)
R
1

Here is what I will do

Class UsersController < ApplicationController
    def index
        @users = User.paginate(:all, :page => params[:page], :per_page => params[:number_of_records])
    end
end
Revocable answered 15/8, 2009 at 6:0 Comment(1)
If OP wants to ensure that only 10, 20 and 50 are valid per page options, you could extend this method to enforce that constraint. Something like ['10', '20', '50'].include?(params[:page])Honeysucker

© 2022 - 2024 — McMap. All rights reserved.