2016-04-20 2 views
0

です。each_sliceを使用して2列の表を出力しています。each_sliceを使用して表を作成しますが、サブ見出しは

私は、反復処理中の要素の属性が変更されたときにタイトル行を挿入したいと考えています。

私が持っている:

all_users = Users.order('category, name asc').all 
all_users.each_slice(2) do |two_users| 
    <tr> 
      <td style="text-align:right"> 
       <%= two_users[0].category + ' - ' + two_users[0].name %> 
      </td> 
      <% if two_users[1].present? %> 
      <td> 
       <%= two_users[1].category + ' - ' + two_users[1].name %> 
      </td> 
      <td> 
      <% else %> 
      <td></td> 
      <% end %> 
    </tr> 
<% end %> 

をそして何か希望:

current_category = '' 
all_users = Users.order('category, name asc').all 
all_users.each_slice(2) do |two_users| 
     <% if two_users[0].category != current_category 
     current_category = two_users[0].category 
    %> 
    <tr><td colspan="2"><%= two_users[0].category %></td></tr> 
    <% end %> 
    <tr> 
      <td style="text-align:right"> 
       <%= two_users[0].name %> 
      </td> 
      <% if two_users[1].present? %> 
      <td> 
       <%= two_users[1].name %> 
      </td> 
      <td> 
      <% else %> 
      <td></td> 
      <% end %> 
    </tr> 
<% end %> 

これはtwo_usersは、[1]新しいカテゴリを有している場合には明らかに動作しませんが。 私は、各カテゴリを反復処理し、それぞれを独立してユーザーに を要求する追加のSQLクエリを回避しようとしています。ここ

答えて

0
all_users.each_slice(2).with_object({cc: nil}) do |two_users, memo| 
    if category = two_users.detect { |u| u.category != memo[:cc] } 
    # print additional row or do whatever here 
    memo[:cc] = category 
    end 
end 

Enumerable#detectは変化がなかった場合は、変更カテゴリまたはnilのいずれかを返します。

追記DRYに試してみてください。

<td> 
    <%= two_users[1].name if two_users[1].present? %> 
</td> 
+0

Mudasobwa、私はこの提案をいじっし、それが仕事を得ることができませんでした。私はメモ[:cc] =カテゴリはメモ[:cc] = category.categoryでなければならないと信じています。また、反復処理の2人のユーザーのそれぞれが異なるカテゴリを持つ場合、最初の新しいカテゴリが印刷され、2番目のユーザーが最初のユーザーのカテゴリ見出しの下に出力されるため、これが機能するとは思わない。ありがとう – SamH

関連する問題