Reputation: 1086
What would be the best method to loop multiple variables into one table? Each variable could have one or more data points. For example, I wish to create something like this:
The following code example is only placing each item in a row.
<table class="table">
<% (@variable1 + @variable2 + @variable3).each do |data, v2, v3| %>
<tr>
<% if data.is_a?(Variable1) %>
<td><%= data.date %></td>
<td><%= data.name %></td>
<% elsif data.is_a?(Variable2) %>
<td><%= data.date %></td>
<td><%= data.name %></td>
<% elsif data.is_a?(Variable3) %>
<td><%= data.date %></td>
<td><%= data.name %></td>
<% end %>
</tr>
<% end %>
</table>
Upvotes: 0
Views: 341
Reputation: 369
In this case, since you don't know how many records might be in each array, I would find out the greatest length of the arrays I have.
In your controller for this aciton could do something like:
@max_length = [@variable_1, @variable_2, @variable_3].map(&:size).max
*Note: this assumes those variables are always arrays, even if they only have a length of 1.
Then in your view file you could do this:
<table class="table">
<% @max_length.times do |n| %>
<tr>
<td><%= @variable_1[n].try(:date) %></td>
<td><%= @variable_1[n].try(:name) %></td>
<td><%= @variable_2[n].try(:date) %></td>
<td><%= @variable_2[n].try(:name) %></td>
<td><%= @variable_3[n].try(:date) %></td>
<td><%= @variable_3[n].try(:name) %></td>
</tr>
<% end %>
</table>
This way, for the third row, for example, in columns 1 and 3 in your example there will be no values, but values for the second column, which has a third record, will appear.
Upvotes: 1