2

所以我有一个检索记录的 SQL 语句:

def total_sales_category_csv

  query1 = "SELECT categoryname, casecost, product_name..."

  result1 = ActiveRecord::Base.connection.execute(query1)

  query2 = "SELECT categoryname, foo, bar..."

  result2 = ActiveRecord::Base.connection.execute(query2)

  result3 =  "SELECT SUM(inv_figures1.available) ..."

  bottle_sum = ActiveRecord::Base.connection.execute(query_for_bottle_sum)


  report = FasterCSV.generate do |csv|
    csv << %w{Category casecost product_name Total Sales Avg}

    #I'm stuck here
  end

end

所以在我被卡住的部分,我如何ActiveRecord::Base.connection.execute以面向对象的方式遍历我返回的记录?我可以做这样的事情:

  report = FasterCSV.generate do |csv|
    csv << %w{Category casecost product_name Total Sales Avg}
    result1.each do |row|
      csv << [result1.categoryname, result2[0].foo] 

    end
  end

?

4

2 回答 2

3

您的结果是一个以列名作为键的哈希。所以你可以像下面一样访问它们

result1.each do |row|
  csv << [result1["categoryname"], result2[0]["foo"]] 

end
于 2013-06-28T21:19:51.927 回答
1

如果您使用自定义 SQL 来获取记录,我建议您使用 find_by_sql ,如下所示:

query1 = "SELECT categoryname, casecost, product_name..."
result1 = MyModel.find_by_sql(query1)

result1.each do |row|
  csv << [row.categoryname, row.casecost, row.product_name]
end

find_by_sql 返回一个 activerecord 对象数组,所以你只是在数组上循环。

于 2013-06-28T21:24:33.010 回答