ב"ה

Blog do Adler Medrado

Blog do Adler Medrado

Jan 10 / 6:06am

Paginação fácil com Rails: will_paginate

English translation is below

INTRODUÇÃO

Uma coisa simples mas normalmente chata de se fazer na mão é a paginação de conteúdo, mas a maioria dos frameworks para desenvolvimento, independente da linguagem em que foi escrito conta com algum componente responsável por esta funcionalidade que apesar de simples ninguém gosta de escrever na mão do zero.

Eu já falei sobre o Zend_Paginator a bastante tempo atrás e você pode ver aqui e hoje vou falar sobre um componente que realiza o mesmo trabalho só que no framework Ruby on Rails.

will_paginate

Existem vários plugins para paginação no Rails mas daqueles que eu testei, este foi o que achei o mais simples de usar.

O código dele está disponibilizado no github e pode ser utilizado como gem, plugin ou por meio de um tarball que é disponibilizado para download.

A instalação dele é bem simples e como gem pode ser feita da seguinte forma:

gem install will_paginate

Para instalar como plugin:

script/plugin install git://github.com/mislav/will_paginate.git

Pronto! Agora vou mostrar como utilizar.
Supondo que você tenha uma model chamada User e queira paginar o conteúdo retornado da tabela Users, você invoca o método paginate informando a página atual e a quantidade de registros por página. 
Caso queira incluir condições em sua consulta, você pode fazer normalmente como se faz em qualquer consulta utilizando uma model gerada pelo rails, o código abaixo demonstra esta situação:

@users = User.paginate :page => params[:page], :per_page => 10, :conditions => ["status = :active", {:active => 'A'}]

Na view nós devemos incluir o trecho de código que monta os botões/links de paginação:

<%= will_paginate @users %>

CONSIDERAÇÕES FINAIS

Existem outros recursos deste plugin que podem ser explorados por exemplo, mudar o layout do controle de paginação porém, não irei aborda-los aqui neste post porque minha intenção é sempre ser o mais breve e simples possível. 

Para maiores informações, dê uma olhada na página deste componente no github: http://github.com/mislav/will_paginate

Abraço!!! 

In English

INTRODUCTION

A simple thing but usually boring to do by the hand is the content pagination, but in most frameworks for development, regardless of what language it was written has some component responsible for this feature that although simple one likes to write from scratch.

I've talked about the Zend_Paginator a long time ago as you can see (brazilian portuguese only) here, and  today and I will talk about a component that performs the same job but in the Ruby on Rails framework.

will_paginate

There are several plugins for pagination in Rails but of those I tested, this was what I found the simplest to use.

The code it is available on github and can be used as a gem, plugin or through a tarball that is available for download.

The installation is pretty simple and as gem can be made as follows:

gem install will_paginate

Plugin Installation:

script/plugin install git://github.com/mislav/will_paginate.git

Ready! Now I'll show how to use.

Assuming you have a model called User and you want to paginate the content returned from the Users table, you invoke the method paginate informing the current page and number of records per page.
If you want to include conditions in your query, you can usually do as is done in any query using a model generated by the rails, the code below demonstrates this:

@users = User.paginate :page => params[:page], :per_page => 10, :conditions => ["status = :active", {:active => 'A'}]

In the view we need to include the code snippet that create the buttons/links pagination.

<%= will_paginate @users %>

FINAL THOUGHTS

There are other features of this plugin that can be exploited,  for example,  change the layout of the pager control but i will not address them here in this post because my intention is to always be as short and simple as possible.

For more information, check out the page of this component on github: http://github.com/mislav/will_paginate

Cheers.
Loading mentions Retweet

0 comments

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    twitter