shroy
shroy

Reputation: 918

Rails 4.2: Rake Task to Import CSV Issue

I have a rake task that should import a .csv file and save the data into the database. So far it runs but when I check the database - nothing was saved and I see no errors - leaving me with no direction.

I'm using Rails 4.2 with Postgresql for the db.

Here is my task..

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

Upvotes: 0

Views: 123

Answers (1)

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

Can you try to replace

User.create

with

User.create!

so if there is any problem with creation it raise.

Upvotes: 3

Related Questions