Ruby on rails 3 使用Rails对数据进行分组和分页

Ruby on rails 3 使用Rails对数据进行分组和分页,ruby-on-rails-3,pagination,will-paginate,Ruby On Rails 3,Pagination,Will Paginate,我有csv导入表模型: class ImportTable < ActiveRecord::Base has_many :import_cells, :dependent => :destroy end class ImportCell < ActiveRecord::Base belongs_to :import_table end 导入单元格有一个行索引和列索引,我在视图中按列对它们进行分组 <table border="1" cellspacing

我有csv导入表模型:

class ImportTable < ActiveRecord::Base
   has_many :import_cells, :dependent => :destroy
end

class ImportCell < ActiveRecord::Base
    belongs_to :import_table
end
导入单元格有一个
行索引
列索引
,我在视图中按列对它们进行分组

<table border="1" cellspacing="1" cellpadding="1">
<tr>
  <% 0.upto(@column_index_max) do |column_index| %>
    <th>
      <%= f.select(column_index, []) %>
    </th>
  <% end %>
</tr>
<% 0.upto(@row_index_max) do |row_index| %>
<% row = @import_cells.select { |cell| cell.row_index == row_index } %>
<tr>
  <% 0.upto(@column_index_max) do |column_index| %>
    <td>
      <%= row.select { |cell| cell.column_index == column_index }[0].contents %>
    </td>
  <% end %>
</tr>
<% end %>
</table>
不太有效,因为将有由
will\u paginate
创建的零对象需要处理。在我看来,这种观点有太多的逻辑性。在这里采取什么好方法?我正在考虑添加一个
row
方法来对
importable
模型本身中的列进行分组,但它必须灵活,这取决于特定表中有多少列。然后可以对行进行分页


任何想法,建议和轻推在“轨道方式”的方向感谢

在我正在工作的站点中,我们有一个类似的设置,我的处理方法如下:

在控制器中构建一个“表”(实际上是一个数组数组):

@table = []
max_col = 0
@table_cells.each do |cel|
    @table[cel.row] ||= []
    @table[cel.row][cel.col] = cel
    max_col = [max_col, cel.col].max
end

#This bit fleshes out your rows with nils to ensure you have a rectangular table:
# (edited to handle empty rows properly)
@table.each_with_index do |row, i|
    @table[i] = [] unless row
    @table[i][max_col] ||= nil
end
在视图中,您只需在表格中循环并显示CEL:

<table>
<% @table.each do |row| -%>
    <tr>
<% row.each do |cel| -%>
        <td><%=h cel.whatever %></td>
<% end -%>
    </tr>
<% end -%>
</table>

这种方法的缺点是,在呈现页面之前,您必须在内存中构建整个表(如果列排序正确,您可能一次只生成一行)。好处是它非常好地坚持MVC(以及“Rails方式”),而且一旦有了构建它的函数,
@table
就非常有用了——一旦有了它,只要调整视图,就可以输出任何想要的格式。我们将其用于HTML和CSV,并计划一旦有人有时间学习该格式,就添加XLS

@table = []
max_col = 0
@table_cells.each do |cel|
    @table[cel.row] ||= []
    @table[cel.row][cel.col] = cel
    max_col = [max_col, cel.col].max
end

#This bit fleshes out your rows with nils to ensure you have a rectangular table:
# (edited to handle empty rows properly)
@table.each_with_index do |row, i|
    @table[i] = [] unless row
    @table[i][max_col] ||= nil
end
<table>
<% @table.each do |row| -%>
    <tr>
<% row.each do |cel| -%>
        <td><%=h cel.whatever %></td>
<% end -%>
    </tr>
<% end -%>
</table>