Rails 3: retrieving different attribute depending on loop count?
I have a loop in one of my views to display a table like so:
Each category object has 5 attributes called: level_1, level_2, level_3, level_4, level_5.
There will be an array with all the category objects. so there could be any amount of categories and no necessarily 3.
what would the best way to draw this up be? i have something like this at the moment but dont know how to select the relevant category level attribute in the 5.times loop.
<table border="0">
<tr>
<th>Maturity</th>
<% for category in @categories %>
<th><%= category.category_title %></th>
<% end %>
</tr>
<% 5.times do |i|%>
<% level = 5 - i %>
<tr>
<td>Level <%= level %> Maturity</td>
<% for category in @categories %>
<td><%= category.level_ #put in the level value here so it selects the relevant attraibute %></td>
<% 开发者_开发技巧end %>
</tr>
<% end %>
</table>
you need to change the rendering of level with this:
<% for category in @categories %>
<td><%= category.send("level_#{level}") %></td>
<% end %>
send is used to call a method on an object so that you can compose your method at runtime.
If you categories as variable no. then you shouldn't make it columns, but rows. And then levels will be you columns e.g.
<table>
<tr>
<th>Level 1</th>
<th>Level 2</th>
<th>Level 3</th>
<th>Level 4</th>
<th>Level 5</th>
<tr>
<% @category.each do |c| %>
<tr>
<td>@category.level_1<td>
<td>@category.level_2<td>
<td>@category.level_3<td>
<td>@category.level_4<td>
<td>@category.level_5<td>
<th>
<% end %>
Now in above code you may replace hard coded level_#{no} with iterations.
精彩评论