0

如何按列而不是按行将数据添加到 csv 文件。

我目前拥有的:

  def self.as_csv(rating_id)
    CSV.generate do |csv|
      csv << ["set_id","item_id", "aggregated_rating", "related_item_id", "rating", "time"]
      product_ids = RatingSet.find(rating_id).products
      product_ids.each do |product|
       recommendation_ids =Recommendation.find(:all, :joins => :products, :conditions => ["product_id = ? and rating_set = ?", product.id, rating_id])
        recommendation_ids.each do |recommendation|
          Rating.find(:all, :conditions => ["recommendation_id = ? and rating_set = ? and product_id = ?", recommendation.id, rating_id, product.id]).each do |rating|
           time_updated = (rating.updated_at)
            csv <<  [rating_id, product.id, product.rating, recommendation.id, rating.rating, time_updated]
          end
        end
      end
    end
  end

这基本上为每组数据生成新行,例如:

102 4433175 2.4 10391793    1   2013-03-26 18:33:40 UTC 
102 4433175 2.4 10391794    1   2013-03-26 18:33:40 UTC 
102 4433175 2.4 12526899    1   2013-03-26 18:33:40 UTC 
102 4433175 2.4 19235377    1   2013-03-26 18:33:40 UTC 

如何通过添加新列而不是行来生成它:

102 4433175 2.4 10391793    1   10391794    1   12526899    1   19235377    1   2013-03-26 18:33:41 UTC
4

1 回答 1

0

你可以使用group_by.

如果性能不是问题,您也可以这样做

 def self.as_csv(rating_id)
    CSV.generate do |csv|
      csv << ["set_id","item_id", "aggregated_rating", "related_item_id", "rating", "time"]
      product_ids = RatingSet.find(rating_id).products
      product_ids.each do |product|
       recommendation_ids =Recommendation.find(:all, :joins => :products, :conditions => ["product_id = ? and rating_set = ?", product.id, rating_id])
        recommendation_ids.each do |recommendation|
          rattings = Rating.find(:all, :conditions => ["recommendation_id = ? and rating_set = ? and product_id = ?", recommendation.id, rating_id, product.id]).map { |r| [r.ratting, r.updated_at] }.flatten
            csv << ([rating_id, product.id, product.rating, recommendation.id] + rattings)
          end
        end
      end
    end
  end
于 2013-04-16T03:33:38.137 回答