Topic: Nested Loops and Pagnation

With this snippet of code I can organize games into categories on a page. The problem is I can't find a way to limit the amount of games that are displayed using paginate or anything else. It also probably shouldn't all be in the rhtml file but , that is the way it is because I can't figure out how to do it any other way. Help is greatly appreciated.

<table>
<%  @categories = Category.find(:all) %>
<% for category in @categories%>
<tr>
<% @games = Game.find_all_by_category_id(category.send('id')) %>
<td><h2><%= category.send('title') %></h2></td>
<% for game in @games %>
    <td><%= link_to game.send('title'), :action => 'show', :id => game.send('id') %></td>
<% end %>
</tr>
<% end %>
</table>

Last edited by kamhp (2006-12-04 16:27:25)

Re: Nested Loops and Pagnation

You need to create a custom paginator in the controller, and use a call that looks something like this to build the paginator:

Games.find(:all, :include => 'categories', :order => 'categories.title')

Re: Nested Loops and Pagnation

Could you elaborate please?

Re: Nested Loops and Pagnation

The standard Rails paginator isn't exactly the nicest part of the api. I'd suggest looking in to this gem:

http://codefluency.com/2006/10/24/paginator-released

It seems a lot more flexible.. It's worked wonders for me at least wink

As for cleaning up the code, if your model associations are properly set up you should be able to do this:

<table>
  <% @categories = Category.find(:all) -%>
  <% for category in @categories%>
  <tr>
    <td><h2><%= category.title %></h2></td>
    <% for game in category.games %>
    <td><%= link_to game.title, :action => 'show', :id => game.id %></td>
    <% end %>
   </tr>
<% end %>
</table>

This is assuming categories related to games with a has_and_belongs_to_many or similar association.
As you can see there's also no need to send() the column names unless they're variables.

And as you said, conventionally you'd put the "@categories = Category.find(:all)" statement in the controller.