You can do this 2 ways. This simpler approach is to group your rows before you present them using group_by
(this assumes Ruby 1.8.7 or later):
<% @client_groups = @data.group_by{|toy| toy.client } %>
<% @client_groups.each do |client, toys| %>
<tr><td>Client Id</td><td>Client Name</td></tr>
<tr><td><%= client.id %></td><td><%= client.name %></td></tr>
<tr>
<td></td>
<td>Name Toy</td>
<td>State Toy</td>
<tr>
<% toys.each do |toy| %>
<tr>
<td></td>
<td><%= toy.name %></td>
<td><%= toy.status %></td>
</tr>
<% end %>
<% end %>
The other approach would be to group using SQL/ActiveRecord, which will actually be more efficient. I don't recall the exact format used in Rails 2.x, but it should be something like this:
@client_groups = Toy.find(:all, :include => :client,
:conditions=>['status IN (0,1,2)' ],
:group => 'client_id' )
And then use the already grouped @client_groups
collection as above.
Note that I used :include
to eager load the client
association (to avoid an N+1 situation where each toy triggers an additional query to the server to find the client) - this should be done regardless of the grouping strategy. You can also refactor your controller code to keep it DRY:
status_condition = params[:status]=="3" ?
['status IN (0,1,2)'] :
['status= ?',params[:status] ]
@data= Toy.find(:all, :conditions=> status_condition,
:include => :client) # add :group if grouping in the query