2013-06-28 52 views
1

所以我有一個SQL語句,我檢索記錄:ActiveRecord :: Base.connection.execute + CSV:如何遍歷返回的列?

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 

回答

2

您的結果是一個以列名作爲鍵的散列。所以您可以訪問他們像下面

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

end 
0

如果您使用自定義的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對象的數組,這樣,那麼你只是在數組上循環。

相關問題