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”
Comments
5 Responses to “How to paginate HABTM relationships in Ruby on Rails”
Leave a Reply








My name is Alex Nesbitt. This is my blog. I publish Digital Podcast where I evangelize new media and marketing innovation, with a focus on digital media, social media, social networks, social analytics and influencer marketing.
Hi Alex,
Thanks for the advice, just waht I was looking for!
Jason Green
Thanks,
Neo
Very helpful! I was worried pagination through HABTM was going to be painful, but it is clean and works nicely.
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?
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.