2012-06-20 33 views
2

目標:使用與我的HTML表格中的信息相似的3個關聯模型生成Excel文檔。 to_xls gem需要這個作爲數組列表。從Rails 3.2中的數組調用ActiveRecord關聯方法

https://github.com/splendeo/to_xls

所需的輸出:

(working for both)  (working for both) (working in HTML, not in Excel) 
territory.branch.name territory.zip territory.mailedcounts.maximum(:maileddate) 
My Branch    90210   2012-05-01 
My Branch    90211   2012-05-03 
My Branch    90212    

分支機構有許多領土。 一個地區有許多Mailedcounts。

我可以調出正確的數據在我看來,通過內置的ActiveRecord的方法show.html.erb

<% for territory in @territories %> 
<tr> 
    <td><%= territory.branch.name %></td>  
    <td><%= territory.zip %></td> 
    <td><%= territory.mailedcounts.maximum(:maileddate) %></td> 
</tr> 
<% end > 

這是我正確的出口至今

class BranchesController < ApplicationController 
. 
. 
. 
def show 
    @branch = Branch.find(params[:id]) 
    @territories = @branch.territories 

    respond_to do |format| 
    format.html 
    format.xls { 
     send_data @territories.to_xls(:columns => [ { :branch => :name }, :zip ]) 
    } 
end 
end 

哪給我territory.branch.name和territory.zip這兩個工作正常。從領土開始,我無法弄清楚如何獲得我的mailedcounts信息。

回答

1

這是爲我做的解決方案。 (經過比本應該花費的更多時間)

訣竅是在Mailedcount模型中定義一個類,而不是Territory模型。

class Mailedcount < ActiveRecord::Base 
. 
. 
. 
    belongs_to :branch 
    belongs_to :territory 

    class << self 
    def max_maileddate 
     maximum('maileddate') 
    end 
    end 
end 

回到控制器我現在可以調用該方法。

class BranchesController < ApplicationController 
. 
. 
. 
def show 
    @branch = Branch.find(params[:id]) 
    @territories = @branch.territories 

    respond_to do |format| 
    format.html 
    format.xls { 
    send_data @territories.to_xls(:columns => [ { :branch => :name }, :zip, 
         { :mailedcounts => :max_maileddate } ]) 
    } 
    end 
    end 

我不能讓一個範圍或者方法在領土模型的工作,而基本上不復制與其他加盟關係。

1

使用自定義範圍應該爲此工作。

class Territory < ActiveRecord::Base 
    scope :mailed_counts_max_date, lambda { 
    mailcounts.maximum(:maileddate) 
    } 
end 

然後在控制器:

class BranchesController < ApplicationController 
def show 
    @branch = Branch.find(params[:id]) 
    @territories = @branch.territories 

    respond_to do |format| 
    format.html 
    format.xls { 
     send_data @territories.to_xls(:columns => [ { :branch => :name }, :zip, :mailed_counts_max_date ]) 
    } 
end 
end 
+0

非常好。我可以用它來從我的控制器中獲取邏輯並查看。 (就像一個文明的人。)現在遇到一個愚蠢的錯誤,明天會再試一次。 –

+0

我注意到你有「mailedcounts」和「mailcounts」的混合......可能是你的bug的原因? –

+0

謝謝你的幫助克里斯,你讓我指出了正確的方向。通過調用內置的ActiveRecord關聯方法來創建範圍的語法給了我一個沒有方法定義的錯誤。不確定這是否是由設計或如果我搞砸了。它看起來像領土模型中的範圍或類是阻力最小的路徑。 –

1

您是否嘗試過(沒有經過測試)

format.xls { 
    # essentially replicate what the view does 
    arr = [] 
    for territory in @territories 
    arr << [territory.branch.name, territory.zip, territory.mailedcounts.maximum(:maileddate)] 
    end 
    send_data arr.to_xls 
} 

如果它(?寶石)預計陣列的列表,那裏有什麼神聖不可侵犯使用ActiveRecord ...

+0

再次感謝您的回覆。我無法完成這項工作,這只是因爲它給我的額外靈活性而令人失望。每當我接近to_xls寶石內的某個東西時都會抱怨。 –

相關問題