[英]Rails 4.2: Rake Task to Import CSV Issue
我有一個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
你能替換嗎
User.create
與
User.create!
因此,如果創作有任何問題,就會引發。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.