我已經查看了其他有關使用回形針創建CSV的文章,但爲何這種方式無法正常工作,我仍然有點失落。我有一個生成(使用CSV.generate)一個CSV字符串的方法,我嘗試將其與下面的方法保存到一個報告在報告控制器:如何使用回形針上傳CSV
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的文檔,但我對它有點新手。
謝謝!
哇,感謝所有這些!有沒有辦法調用控制器方法創建呢? – trevorhinesley
通常情況下,您不會在瀏覽器或API請求之外調用控制器方法。假設您已使用RESTful資源設置路由,您需要向您的應用程序發送POST請求。那有意義嗎? –
是的,我把所有這些放在模型中。謝謝!! – trevorhinesley