0

我查看了有关使用 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 的文档,但我对它有点陌生。

谢谢!

4

1 回答 1

0

这里发生了很多事情:)

首先,看起来你让你的控制器和模型感到困惑。在 rake 任务中,Report是模型,但您调用 create 时就好像它是控制器方法一样。模型(又名 ActiveRecord 类)采用键/值对:

Report.create(type: "Geo")

另一个问题是您使用“类型”作为列名,这将告诉 ActiveRecord 您正在使用单表继承。这意味着您有报告的子类。除非您真的需要 STI,否则您应该重命名此列。

最后,您不应该有一个带有参数的控制器方法。我不太确定你想在那里做什么,但控制器通过 params 哈希获取他们的参数。

于 2013-09-24T21:50:24.460 回答