Goal: Produce an Excel document with information from 3 associated models that is similar to that in my HTML table. The to_xls gem requires this as a list of arrays.
https://github.com/splendeo/to_xls
Desired output:
(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
A Branch has many Territories.
A Territory has many Mailedcounts.
I can bring up the correct data in my view via the built in ActiveRecord methods for 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 >
This is what I have correctly exporting so far
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
Which gives me territory.branch.name and territory.zip which both work properly. Starting from territory I can’t figure out how to get at my mailedcounts info though.
This is the solution that did it for me. (After far more hours of trying than it should have taken.)
The trick was to define a class in the Mailedcount model, not the Territory model.
Back to the controller I can now call that method.
I couldn’t get a scope or method to work in the Territory model without essentially reproducing the relationship with another join.