2011-02-02 3 views
-1

나는 CSV 가져 오기 테이블 모델이 있습니다데이터 그룹화 및 페이지 매김

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, 내가 그룹을이를 보기에서 열별로

<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_paginate에 의해 만들어진 객체 전무가있을 것 같은

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

가 잘 작동을하지 않습니다. 보기에는 너무 많은 논리가있는 것 같습니다. 여기서 취하는 좋은 접근 방법은 무엇입니까? 나는 ImportTable 모델 자체의 컬럼을 그룹화하기 위해 row 메소드를 추가하려고 생각하고 있지만, 특정 테이블에 얼마나 많은 컬럼이 있는지에 따라 유연해야한다. 그러면 행에 페이지가 매겨 질 수 있습니다.

"레일 방식"방향의 모든 생각, 제안 및 뉘앙스가 인정되었습니다!

답변

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 

그리고보기 , 당신이해야 할 모든 테이블을 반복하고 CELS를 보여

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

이 방법의 단점은 R 전에 메모리에 전체 테이블을 구축해야한다는 것입니다 페이지를 작성하는 것입니다 (열을 적절하게 정렬하면 한 번에 한 행씩 처리 할 수 ​​있습니다). 장점은 MVC (그리고 "Rails Way")에 꽤 잘 고착되어 있고, 일단 함수를 빌드하면 @table은 매우 유용하다는 것입니다. 일단 그것을 가지고 나면 방금 원하는 모든 형식을 출력 할 수 있습니다 보기 조정. 우리는 HTML 및 CSV 용으로 사용하고 누군가가 형식을 습득하자마자 XLS를 추가 할 계획입니다.