我查看了有关使用 Paperclip 创建 CSV 的其他帖子,但对于为什么这不起作用仍然有点迷茫。我有一个生成 CSV 字符串的方法(使用 CSV.generate),我尝试使用以下方法将其保存到报告控制器中的报告中:
def create(type)
case type
when "Geo"
csv_string = Report.generate_geo_report
end
@report = Report.new(type: type)
@report.csv_file = StringIO.new(csv_string)
if @report.save
puts @report.csv_file_file_name
else
@report.errors.full_messages.to_sentence
end
end
但是,在执行时,我得到一个undefined method 'stringify_keys' for "Geo":String
错误。这是报告模型:
class Report < ActiveRecord::Base
attr_accessible :csv_file, :type
has_attached_file :csv_file, PAPERCLIP_OPTIONS.merge(
:default_url => "//s3.amazonaws.com/production-recruittalk/media/avatar-placeholder.gif",
:styles => {
:"259x259" => "259x259^"
},
:convert_options => {
:"259x259" => "-background transparent -auto-orient -gravity center -extent 259x259"
}
)
def self.generate_geo_report
male_count = 0
female_count = 0
csv_string = CSV.generate do |csv|
csv << ["First Name", "Last Name", "Email", "Gender", "City", "State", "School", "Created At", "Updated At"]
Athlete.all.sort_by{ |a| a.id }.each do |athlete|
first_name = athlete.first_name || ""
last_name = athlete.last_name || ""
email = athlete.email || ""
if !athlete.sports.blank?
if athlete.sports.first.name.split(" ", 2).first.include?("Women's")
gender = "Female"
female_count += 1
else
gender = "Male"
male_count += 1
end
else
gender = ""
end
city = athlete.city_id? ? athlete.city.name : ""
state = athlete.state || ""
school = athlete.school_id? ? athlete.school.name : ""
created_at = "#{athlete.created_at.to_date.to_s[0..10].gsub(" ", "0")} #{athlete.created_at.to_s.strip}"
updated_at = "#{athlete.updated_at.to_date.to_s[0..10].gsub(" ", "0")} #{athlete.updated_at.to_s.strip}"
csv << [first_name, last_name, email, gender, city, state, school, created_at, updated_at]
end
csv << []
csv << []
csv << ["#{male_count}/#{Athlete.count} athletes are men"]
csv << ["#{female_count}/#{Athlete.count} athletes are women"]
csv << ["#{Athlete.count-male_count-female_count}/#{Athlete.count} athletes have not declared a gender"]
end
return csv_string
end
end
这是从 cron 作业 rake 任务中调用的:
require 'csv'
namespace :reports do
desc "Geo-report"
task :generate_nightly => :environment do
Report.create("Geo")
end
end
不知道从哪里开始获得此功能。有什么建议么?我一直在阅读 Paperclip 的文档,但我对它有点陌生。
谢谢!