Übersetzungen dieser Seite?:

Pagination in Ruby on Rails Projekten

Häufig kommt es vor, das in den Views nicht alle Einträge einer Datenbanktabelle auf einmal ausgegeben werden sollen, sondern verteilt auf verschiedene Seiten. Diese Funktionalität bietet das WillPaginate gem.

NOTE: WillPaginate setzt Rubygems in Version 1.2 vorraus.

(Der Großteil der hierzufindenden Informationen stammt von der offiziellen WillPaginate Dokumentation.)

Installation

Das WillPaginate gem befindet sich auf GitHub. Um es zu installieren, muss zuerst GitHub zu den gem sources dazugefügt werden:

$ gem sources -a http://gems.github.com

Jetzt kann das Gem installiert werden:

$ gem install mislav-will_paginate

Das Gem laden

To enable the library your Rails 2.0.x (or even 1.2.x) project, load it in „config/environment.rb“

Rails::Initializer.run do |config|
  ...
end
 
require "will_paginate" 

Don't put it before or inside the Rails::Initializer block because the Rails framework is not yet loaded at that point of execution.

In Rails 2.1 (or greater) you can use Gem dependencies to load the will_paginate gem, simply add the following code to config/environment.rb:

Rails::Initializer.run do |config|
...
  config.gem 'mislav-will_paginate', :lib => 'will_paginate', :source => 'http://gems.github.com'
end

Beispiele

Verwendung des paginate finders im Controller:

@posts = Post.paginate_by_board_id @board.id, :page => params[:page], :order => 'updated_at DESC'

Die paginate Methode funktioniert fast genauso wie find - außer dass es nicht alle Einträge abruft. Vergiss nicht die Seitennummer anzugeben, oder eine Fehlermeldung wird ausgegeben! Mehr zu WillPaginate::Finder::ClassMethods

Die Posts können genau wie ohne Pagination ausgegeben werden. Um die Navigationselemente anzuzeigen, muss nur das hier eingefügt werden:

<%= will_paginate @posts %>

Will_paginate determines how many records to display per page by calling the per_page class method for the model being returned by the query. You can define the per_page method like this:

class Post < ActiveRecord::Base
  cattr_reader :per_page
  @@per_page = 50
end

… or like this:

class Post < ActiveRecord::Base
  def self.per_page
    50
  end
end

… or don’t worry about it at all. WillPaginate defines it to be 30 by default. But you can always specify the count explicitly when calling paginate in your controller:

@posts = Post.paginate :page => params[:page], :per_page => 50

The paginate finder wraps the original finder and returns a resultset that has some extra properties. You can use the returned collection as you would with any ActiveRecord resultset. WillPaginate view helpers also need that object to be able to render pagination:

<ol>
  <% for post in @posts -%>
    <li>Render 'post' in some nice way.</li>
  <% end -%>
</ol>

Weiterführende Seiten

 
de/howtos/pagination.txt · Zuletzt geändert: 2009/02/10 19:19 von nosilume
 
Recent changes RSS feed Creative Commons License