【发布时间】:2014-08-15 20:13:47
【问题描述】:
通过 Rake 任务导入 CSV 文件并将其存储在多个表中这个看似简单的任务遇到了麻烦。
我的耙子任务:
desc "Imports the COGCC CSV file into wikifrac database"
task :import_cogcc => :environment do
require 'csv'
CSV.foreach('public/partial.csv', :headers => true) do |row|
# create records in independent tables
# create the Company object
this_company_name = row['name'].strip!
this_operator_num = row['operator_num']
if !(Companies.exists?(:company_name => this_company_name))
Companies.create(:company_name => this_company_name, :operator_num => this_operator_num)
end
thecompany = Companies.find(:first, :conditions => ["this_company_name = ?", this_company_name])
company_id = thecompany.id
...
我的公司模型:
class Companies < ActiveRecord::Base
has_many :facilities, dependent: :destroy
attr_accessor :company_name, :operator_num
def initialize(company_name, operator_num)
@operator_num = operator_num
@company_name = company_name
end
end
但是当我运行 rake import_partial 时,我得到了这个错误:
rake 中止! ArgumentError:参数数量错误(1 对 2) wfrails/app/models/companies.rb:5:in
initialize' wfrails/lib/tasks/import_partial.rake:47:inblock(2 级)在 ' wfrails/lib/tasks/import_partial.rake:26:in `block in ' 任务:TOP => import_cogcc
谁能告诉我这有什么问题?一直在兜兜转转; SO中有很多类似的例子,但不能完全解决我的错误......
【问题讨论】:
-
你为什么要覆盖
initialize? ActiveRecord provides several ways 使用其属性批量初始化模型。为什么要向模型添加实例变量?那些不应该存储在数据库中吗? ARcreate方法无法使用您创建的新initialize。 -
只要摆脱你的
initialize方法,一切都会奏效。 -
您可能要考虑使用事务并创建!这样您就不会在 rake 任务失败时创建模型
-
谢谢大家;删除初始化做到了...
标签: ruby-on-rails ruby rake