Reputation: 3383
I'm accessing attributes from several different variables of several different models. I'm trying to find the best way to display these attributes in a table, and I'm getting some unwanted duplication in my view. Here's the relevant part of my table.
<% @list_items.each do |l| %>
<% @i_items.each do |i| %>
<% @details.each do |d| %>
<% @vends.each do |v| %>
<tr>
<td><%= d.product %></td>
<td><%= d.brand %></td>
<td><%= d.details %></td>
<td><%= i.price %></td>
<td><%= v.name %></td>
<td><%= v.address %></td>
<td><%= button_to "Delete", {:controller => :list_items,
:action => 'destroy',
:id => l.id},
:method => :delete %></td>
</tr>
<% end %>
<% end %>
<% end %>
<% end %>
This currently duplicates the rows I want to view by 4x (presumably because I've got 4 do
blocks going on and am not properly using them to achieve my goal. Any tips on how to make this work and what I'm do
-ing wrong (sorry couldn't help myself)? Also open to suggestions about how to do this a bit more cleanly than my silly way of using 4 variables? Thanks in advance!
Upvotes: 0
Views: 136
Reputation: 3383
Thanks to the suggestion of @kristenmills I sort of realized that I had the necessary associations to do this really cleanly with the below code. Someone probably would've pointed this out had I posted all of my associations and given a bit more background.
<% @list_items.each do |l| %>
<tr>
<td><%= l.item.product %></td>
<td><%= l.item.brand %></td>
<td><%= l.item.details %></td>
<td><%= l.inventory_item.price %></td>
<td><%= l.inventory_item.vendor.name %></td>
<td><%= l.inventory_item.vendor.address %></td>
<td><%= button_to "Delete", {:controller => :list_items,
:action => 'destroy',
:id => l.id},
:method => :delete %></td>
</tr>
<% end %>
Upvotes: 1
Reputation: 1297
So what I'm getting from this is you have these 4 lists that you want to iterate over at once? If that is the issue, do something like this:
<% 0.upto(@list_items.count) do |i| %>
<tr>
<td><%= @details[i].product %></td>
<td><%= @details[i].brand %></td>
<td><%= @details[i].details %></td>
<td><%= @i_items[i].price %></td>
<td><%= @vends[i].name %></td>
<td><%= @vends[i].address %></td>
<td><%= button_to "Delete", {:controller => :list_items,
:action => 'destroy',
:id => @list_items[i].id},
:method => :delete %></td>
</tr>
<% end %>
This is making the assumption that all the arrays are the same length and that order has not been altered. This is not really a safe idea and redesigning your models might be something worth looking into.
Upvotes: 2