# Using pagination to group pages by attribute value

**URL:** <https://www.ruby-forum.com/t/using-pagination-to-group-pages-by-attribute-value/164075>\
**Category:** Rails\
**Created:** [March 27, 2009, 3:41pm UTC](https://www.ruby-forum.com/t/using-pagination-to-group-pages-by-attribute-value/164075 "2009-03-27T15:41:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gte351s](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/5f9b8f/32.png) [@gte351s](https://www.ruby-forum.com/u/gte351s)\
**Post date:** [March 27, 2009, 3:41pm UTC](https://www.ruby-forum.com/t/using-pagination-to-group-pages-by-attribute-value/164075/1 "2009-03-27T15:41:12Z")

</div>

Hi -

I’m trying to group records based on some attribute they or an  
association of their’s have. The simplest example I could think of to  
drive my point is this:

## Assume the following model associations (pardon my butchering of rails)

Faculty has\_many :courses  
Course belongs\_to :faculty

I want to paginate courses based on the name of the faculty they belong  
to.

The paging may look something like this (instead of page numbers):

# in the actual view

\<\< prev Archeology Botanics … |Math| … Zoology next \>\>

# listing all courses of current page

I’d appreciate help on how to accomplish that. I know will\_paginate does  
numbering, but I couldn’t figure out if it can do the above.

---

<div class="post-metadata">

**Author:** ![gte351s](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/5f9b8f/32.png) [@gte351s](https://www.ruby-forum.com/u/gte351s)\
**Post date:** [March 31, 2009, 6:16pm UTC](https://www.ruby-forum.com/t/using-pagination-to-group-pages-by-attribute-value/164075/2 "2009-03-31T18:16:39Z")

</div>

Shilo, you might be interested in “group\_by”:

> **[New in Rails: Enumerable#group\_by and Array#in\_groups\_of](https://rubyonrails.org/2006/3/1/new-in-rails-enumerable-group_by-and-array-in_groups_of)**
>
> Changeset 3726 adds two little methods to ActiveSupport: Enumerable#group\_by and @ Array#in\_groups\_of@.Enumerable#group\_by is for collecting an enumerable into sets, grouped by the result of a block. Useful, for example, for grouping records by date....

The first example groups by an attribute (in the above case, “day”).  
Try it in script/console first to see how the data structure is  
returned. It’s a nested array of key, values where the key is the  
attribute and the value is an array of records that are in that group.  
You can iterate through it with the each call as in that example.

HTH!

-Danimal

P.S. I’ve used group by with will\_paginate and it works just fine

On Mar 27, 8:41 am, Shilo A. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
