Rails 4.2:导入CSV问题的Rake任务

时间:2015-06-30 18:09:00

标签: ruby-on-rails ruby postgresql csv rake-task

我有一个rake任务,应该导入.csv文件并将数据保存到数据库中。到目前为止,它运行但是当我检查数据库时 - 没有保存,我看到没有错误 - 让我没有方向。

我正在使用Rails 4.2和Postgresql作为数据库。

这是我的任务..

namespace :import_users do
  desc "imports user data from a csv file"
      task :data => :environment do
            require 'csv'
              CSV.foreach('/Users/RAILS/Extra Files/2015 User Report.csv') do |row|
                  plan                  = row[0]
                  contact_ident         = row[1]
                  prefer_fax            = row[2]
                  pin                   = row[3] 
                  name                  = row[4] #account
                  first_name            = row[5]
                  last_name             = row[6]
                  email                 = row[7]      
                  phone                 = row[8] 

                  prefer_fax == "Yes" ? p_fax = true : p_fax = false

                  p = Plan.where("name ~ ?","#{plan}( )")

                  user = User.create(   contact_ident: contact_ident, 
                                        prefer_fax: p_fax, 
                                        first_name: first_name, 
                                        last_name: last_name, 
                                        email: email
                                    )

                  account = Account.where("pin ~ ?", "#{pin}").first_or_create do |account|
                              account.name  = name
                              account.phone = phone
                            end

                  user.plans    << p
                  user.accounts << account
            end
      end
end

1 个答案:

答案 0 :(得分:3)

您可以尝试替换

吗?
User.create

User.create!

所以如果创作出现任何问题,就会提出。