从Rails 3.2中的数组调用ActiveRecord关联方法

时间:2012-06-20 03:50:37

标签: ruby-on-rails arrays excel activerecord associations

目标:使用与我的HTML表格中类似的3个关联模型的信息生成Excel文档。 to_xls gem需要将其作为数组列表。

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            

分行有许多地区。 领土有许多邮寄帐户。

我可以通过show.html.erb的内置ActiveRecord方法在我的视图中显示正确的数据

<% 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信息。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
}

如果它(gem?)需要一个数组列表,那么使用ActiveRecord就没什么神圣之处......

答案 2 :(得分: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

我无法在Territory模型中使用范围或方法,而基本上不会再现与其他连接的关系。

相关问题