2011-02-02 157 views
-1

我有CSV導入表模型:分組數據和分頁使用Rails

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

class ImportCell < ActiveRecord::Base 
    belongs_to :import_table 
end 

控制器(編輯爲了簡潔):

def show 
    @import_table = ImportTable.find(params[:id]) 

    @import_cells = @import_table.import_cells 
    @row_index_max = @import_cells.map { |cell| cell.row_index }.max 
    @column_index_max = @import_cells.map { |cell| cell.column_index }.max 
end 

的import_cells具有row_indexcolumn_index,I組他們按視圖中的列。

<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> 

我從另一個網站cribbed,這似乎有點janky對我來說。簡單地增加:

@import_cells = @import_table.import_cells.paginate(:all, :order => "row_index ASC", :per_page => @column_index_max * 16, :page => params[:page]) 

完全不是那麼回事一樣會有零有要處理的will_paginate創建的對象。在我看來,這種觀點有太多的邏輯。這裏採取什麼好方法?我正在考慮添加一個row方法來對ImportTable模型本身的列進行分組,但根據特定表中有多少列,它必須靈活。然後行可以分頁。

任何想法,建議,並在「鐵路方式」方向輕度讚賞!

回答

1

我們在該網站類似這樣的設置我的工作,我處理了,如下所示:

在控制器中建立一個「表」(實際上是一個數組的數組):

@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> 

這種方法的缺點是,你必須建立整個表R之前,內存打開頁面(如果你正確地對列進行排序,你可以一次做一行)。好處是,它堅持到MVC(因此「Rails方式」)很好,並且一旦你有一個函數來構建它,@table是非常有用的 - 一旦你有了它,你可以輸出任何你想要的格式調整視圖。我們將它用於HTML和CSV,並計劃在有人有時間學習格式時添加XLS。