I''m just starting out with Rails and Ruby. I have the Agile book and
Pickaxe on order, but have a question for a test project on which I''m
working. I''d appreciate any information or feedback available.
I have a "teams" table and a "players" table. Teams has_many
players and
Players belongs_to team.
I have a list view which shows all of the players. I have the list
method in the controller sorting the players by team, then name. I''d
like to display them in the view as follows:
Team 1 Name:
player 1
player 2
player 3
Team 2 Name:
player 4
player 5
player 6
To do it, I''ve added the following to the player list view:
<% lastTeam = "" %>
<% for player in @players %>
<% if player.team.name != lastTeam %>
<% lastTeam = player.team.name %>
<!-- Show Team Name (e.g., "Header") -->
<tr>
<td colspan="2">
<h1><%= link_to player.team.name, :controller =>
''teams'', :action => ''show'', :id =>
player.team.id %></h1>
</td>
</tr>
<tr>
<!-- Header Row for player (once per team). -->
<th>Player Name</th>
<th>Actions</th>
</tr>
<% end %>
<!-- The detail row for each player goes here. -->
<% end %>
This works, but I''m not sure it is exactly the Rails way. I did it this
way because I have done it in the past for other languages/frameworks in
the past (ColdFusion, JSP, etc.). In looking at it, though, it seems
like it doesn''t exactly fit the "Rails Way". I suppose that
there might
be a better way that is more in keeping with the Rails philosophy. Some
thoughts that occurred to me:
1. Create a helper to display the information, but that seems like it
might just move the HTML out to the helper.
2. Iterate over the teams (unique teams for the list of players), and
get the players for that team, kind of like this pseudo-code:
for team in unique_teams_with_players
display team header
for players in team
display player information
end
end
3. Use some existing capabilities of which I am ignorant because I''m
just starting with Rails.
I looked through the HowTos and other Tips and Tricks, but couldn''t
find
anything which looked right. Thanks for anything anyone can pass along
to help me along the way.
H.B.