How to paginate HABTM relationships in Ruby on Rails

Posted on December 27, 2006
Filed Under General |

I looked everwhere for a quick example of Ruby on Rails pagination with a has_many_and_belongs_to (HABTM) relationship, but could not find any good examples of what the code looks like.

The application is a photo album. Photos can belong to many albums and albums can have many photos.

For the models, I have albums, photos and albums_photos. The albums_photos is the join table and has album_id and photo_id as table fields.

Here is what I used in the controller to make it work.


@album = Album.find params[:id]
@photo_pages, @photos = paginate :photos, {:per_page => 15, :include => ‘albums’,
:conditions => [ 'albums.id =?', @album.id ]}
render :action=>”list”

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Pownce
  • TwitThis

Comments

5 Responses to “How to paginate HABTM relationships in Ruby on Rails”

  1. Jason Green on January 24th, 2007 6:06 am

    Hi Alex,
    Thanks for the advice, just waht I was looking for!
    Jason Green

  2. Neo on February 7th, 2007 11:37 pm

    Thanks,

    Neo

  3. Krishna Dole on February 13th, 2007 11:15 am

    Very helpful! I was worried pagination through HABTM was going to be painful, but it is clean and works nicely.

  4. Manuel on July 13th, 2007 2:59 am

    Thanks! works very well, but, it seems that the only album under @photos[1].albums will be the searched one, the rest of the albums for that photo doesn’t appear. Is there any way to solve that?

  5. alex on July 13th, 2007 6:09 am

    I’m not sure what you’re use case is. This code is returning paginated photos, not paginated albums.

    The code above will display the photos within a specific album. If you had two albums you wanted to return photos for you could pass in the second album’s id in addition to the first and then modify the condition statement to include both albums with an OR statement.

Leave a Reply