目標:使用與我的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信息。
非常好。我可以用它來從我的控制器中獲取邏輯並查看。 (就像一個文明的人。)現在遇到一個愚蠢的錯誤,明天會再試一次。 –
我注意到你有「mailedcounts」和「mailcounts」的混合......可能是你的bug的原因? –
謝謝你的幫助克里斯,你讓我指出了正確的方向。通過調用內置的ActiveRecord關聯方法來創建範圍的語法給了我一個沒有方法定義的錯誤。不確定這是否是由設計或如果我搞砸了。它看起來像領土模型中的範圍或類是阻力最小的路徑。 –