【问题标题】:Rails CSV generationRails CSV 生成
【发布时间】:2013-04-15 20:36:15
【问题描述】:

如何按列而不是按行将数据添加到 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

【问题讨论】:

  • 如果可以构造数组,就可以构造CSV行。

标签: ruby-on-rails ruby ruby-on-rails-3 csv export-to-csv


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2018-03-06
    相关资源
    最近更新 更多