gpt4 book ai didi

ruby-on-rails - Rails 导出 csv,包括连接表属性

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:06 25 4
gpt4 key购买 nike

我的应用程序中有 3 个模型 + 关联的连接表:

评分集:

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

产品:

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

建议:

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

我正在尝试添加导出到 csv 功能。

到目前为止我的方法:

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

我计划添加 scoped 以查找 set_id、time、item_id、related_item_id 和 rating,但为了测试,我使用上面的值。如何遍历每个数组,并将值添加到导出的 csv 文件中各自的标题下?

最佳答案

将下面的方法添加到一个 lib 文件中,并在我的每个 Controller 中调用它。基本上必须一次遍历一个模型,在获得我需要的所有属性后,我附加到 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

关于ruby-on-rails - Rails 导出 csv,包括连接表属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14817931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com