开发者

Rails 3: Looping through array of objects, ignoring the first object in the array?

开发者 https://www.devze.com 2023-03-01 06:42 出处:网络
In my view i am trying to dispaly a table of objects, this is my code: <div id=\'categories_show\'>

In my view i am trying to dispaly a table of objects, this is my code:

<div id='categories_show'>

  <table border="1">
    <tr>
      <th>Categories</th>
      <th>CBB's</th>
    </tr>
    <% for category in @critical_process.categories %>
        <tr>
          <td rowspan="<%= category.capability_building_blocks.size %>"><%= category.category_title %></td>
          <td><%= category.capability_building_blocks.first.cbb_title %></td>

        </tr>
        <% (category.capability_building_blocks - category.capability_building_blocks.first).each do |cbb| %>
        <tr>
          <td><%= cbb.cbb_title %></td>
        </tr>
        <% end %>
    <% end %>

  </table>
</div>

however this is throwing an error saying: can't convert CapabilityBuildingBlock into Array

the relationships are correct, the error is coming from the line where i try subtract the first object of the array here: <% (category.capability_building_blo开发者_JAVA百科cks - category.capability_building_blocks.first).each do |cbb| %>

is there any way i can loop through the array ignoring the first object in the array?

Thanks


Try using Array.drop - http://www.ruby-doc.org/core/classes/Array.html#M000294

<% category.capability_building_blocks.drop(1).each do |cbb| %>
  <tr>
    <td><%= cbb.cbb_title %></td>
  </tr>
<% end %>


Additionally, this is more readable (And I'm 80% sure it works):

<%= category.capability_building_blocks[1..-1].each do |cbb| %>

You can use the built in slice operators to select any elements from an array that you want. -1 represents the last element in the array.


<%= (category.capability_building_blocks - [category.capability_building_blocks.first]).each do |cbb| %>

Also...

stop_here = category.capability_building_blocks.length
category.capability_building_blocks[1..(stop_here)].each do |cbb|
0

精彩评论

暂无评论...
验证码 换一张
取 消