0

部分レンダラー内の状態をどのように記憶できますか?

当面の問題: 私のパーシャル_testitem.html.erbは、testitem のコレクションのテーブル行をレンダリングします。ATestitemには anidと a がsortkeyあり、パーシャルは with で呼び出されます

<%= render :partial => "testitem", :collection => @testbox.testitems.sort_by{|x| [x.sortkey, x.id]} %>

つまり、すべてのテストアイテムはソートキーでソートされ、次に ID でソートされます。ここで、現在のソートキーを示すテーブル列を表示したいと思います。

<td rowspan="<%= Testitem.count_by_sql "SELECT count(*) from testitems where sortkey=#{testitem.sortkey}" %>"><%=h testitem.sortkey %></td>

もちろん、すべての取得が行スパンであるため、これはテーブルを壊します<td>。期待される結果は、次のようになります。

Group   |   Id  |    Description |
----------------------------------
   1    |    1  |    ...         |
        --------------------------
        |    2  |    ...         |
        --------------------------
        |    16 |    ...         |
----------------------------------
   2    |    3  |    ...         |
----------------------------------
   3    |    4  |    ...         |
        |   10  |    ...         |
        |   11  |    ...         |
 ---------------------------------

特定の に既に_testitem.html.erb追加したという事実を(内で) 「覚える」方法はありますか?<td rowspan="">sortkey

助けてくれてありがとう。

4

3 に答える 3

1

あなたのモデルでは、次のようなことができます:

class TestBox  
  named_scope :sorted_items, :sort_by => :sort_key, :id

  def grouped_items
    sorted_items.group_by(&:sort_key)
  end
end

あなたの見解では、次のことができます:

<% @test_box.grouped_items.each do |sort_key, items| %>
  <td rowspan="<% items.length %>"><%= render :partial => 'test_item', :collection => items %></td>
<% end %>

および test_item パーシャルで:

<%= h item.sort_key %>

これがまさにあなたがやろうとしていることが得られるかどうかは完全にはわかりませんが、正しい方向への良いスタートを切ることができます.

于 2009-12-30T23:52:15.203 に答える
1

まず、とにかくテストボックスのすべてのテスト項目を使用する場合、余分なカウント クエリは必要ありません。

あなたがしたいことは、最初のアイテムをグループの td で部分的に描画し、残りのアイテムを定期的に描画することです..

コントローラーで:

@testitems_by_keys = @testbox.testitems.group_by(&:sortkey)

あなたのビューで:

<% @testitems_by_keys.each do |group, items| %>
  <%= render :partial => "item", :locals => { :object => items.shift, :group => group, :size => items.size+1 } %>
  <%= render items %>
<% end %>

_item:

<tr>
<% if local_assigns[:group].present?  %>
  <td rowspan="<%= size %>"><%= group %></td>
<% end %>
rest of the partial....
</tr>

注:ここに書いただけです..構文エラーが含まれている場合と含まれていない場合があります。

于 2009-12-31T00:01:19.897 に答える
0

試すことができる1つの解決策...最初に、各ソートキーに必要なすべての行スパンのハッシュを取得します。

@rowspans = TestItem.count(:group => sortkey)

次に、パーシャルで、各行をレンダリングするときに、インスタンス変数を設定して、現在のソートキーで行をレンダリングしているかどうかを確認します...

<% if testitem.sortkey != @current_sort_key %>
  <% @current_sort_key = testitem.sortkey %>
  <td rowspan="<%= @rowspans[@current_sort_key] -%>">
    <%= testitem.sortkey %>
  </td>
<% end %>
... render the rest of row ...

ビューをどれだけきれいにするかによっては、ビュー自体ではなく、ヘルパーの内部に書き込む方がよい場合があります。

于 2009-12-30T23:05:21.413 に答える