简体   繁体   English

Rails导出csv,包括连接表属性

[英]Rails export csv including join table attributes

I have 3 models in my app + associated join tables: 我的app +关联联接表中有3个模型:

Rating Set: 评级集:

class RatingSet < ActiveRecord::Base
  has_many :product_rating_sets, :dependent => :destroy
  has_many :products, :through => :product_rating_sets
end

Product: 产品:

class Product < ActiveRecord::Base
  has_many :product_recommendations, :dependent => :destroy
  has_many :recommendations, :through => :product_recommendations
  has_many :product_rating_sets, :dependent => :destroy
  has_many :rating_sets, :through => :product_rating_sets  
end

Recommendations: 建议:

class Recommendation < ActiveRecord::Base
  has_many :product_recommendations, :dependent => :destroy
  has_many :products, :through => :product_recommendations
end

I am trying to add an export to csv function. 我试图添加导出到csv函数。

My method so far: 我的方法到目前为止:

def self.as_csv
    CSV.generate do |csv|
      csv << ["set_id", "time", "item_id", "related_item_id", "rating"]
      set_id = ['1','2','3']
      time = ['10:40am', "11:30pm", "14:40am"]
      item_id = ["123456","123456765", "123456543"]
      related_item_id = ["1234565432345","109876532", "564783920"]
      rating = ["12.3", "13.2", "132.2"]

      all.each do |item|
        csv << item.attributes.values_at(*column_names)#lost here
      end
    end
  end

I am planning on adding scoped to find set_id, time, item_id, related_item_id and rating, but for testing, I am using the values above. 我打算添加范围来查找set_id,time,item_id,related_item_id和rating,但是对于测试,我使用的是上面的值。 How to I iterate through each of those arrays, and added the values to the exported csv file under their respective headers? 如何遍历每个数组,并将值添加到各自标题下的导出的csv文件中?

Added the method below to a lib file, and call it in each of my controllers. 将以下方法添加到lib文件中,并在每个控制器中调用它。 Basically had to iterate through one model at a time, and after getting all the attributes I needed, I appended to the csv object. 基本上必须一次迭代一个模型,并在获得我需要的所有属性后,我附加到csv对象。

def self.as_csv(rating_id)
        CSV.generate do |csv|
          csv << ["set_id","item_id", "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 = ?", product.id])
            recommendation_ids.each do |recommendation|
              recommendation.ratings.each do |ratings|
               time_updated = (ratings.updated_at)
                csv <<  [rating_id, product.id, recommendation.id, ratings.rating, time_updated]
              end
            end
          end
        end
      end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM