Failed to import csv to MySQL db in Ruby on Rails 3

I am working on importing data from a CSV file into MySQL db through Ruby on Rails 3. A client model has already been created. In addition, the script below will produce puts row [2] and correctly place line [3]. When I add assignments for the customer.warranty_part_no and warranty_part_desc database fields, it throws an error below.

csv = CSV.read(file, col_sep: ",", headers: false)

c = Customer.new  
csv.each do |row|
        c.warranty_part_no = row[2],
        c.warranty_part_desc = row[3]
end

Here is the error I am getting.

uninitialized constant Customer (NameError)

After some testing, I think this problem arises because I run this script from the command line, therefore the customer.rb model does not execute with the large rails application, therefore the Customer class is never created. How can I run this script from the command line and use ActiveRecord or activerecord-import? If this is not possible, how can I create a route for it or call it from a view in the application?

I am on Ruby 1.9.2 and Rails 3.2.2. Thank you in advance for any advice.

+5
source share
5 answers

The problem, as you understand it, is that the Rails environment does not load. You can do this in a stand-alone script by including the client model, active_record and establishing a connection using your database.yml.

. :

namespace :data do
  desc "Import data from CSV"
  task :import => :environment do
    #Your script here
  end
end

=> :environment rake Rails, .

rake data:import, RAILS_ENV=production, .

+2

, :

 #myscripy.rb
 # add following in your script
 require 'rubygems'
 require 'active_record'
 require YOUR_DB_ADAPTER_GEM #'mysql2', 'pg'
 require PATH_TO_YOUR_MODEL

 csv = CSV.read(file, col_sep: ",", headers: false)

 c = Customer.new  
 csv.each do |row|
    c.warranty_part_no = row[2],
    c.warranty_part_desc = row[3]
 end
 c.save

else rake ( RailsApp)

require 'csv'
 namespace :import do
 task :csv_file => :environment do
  csv = CSV.read(file, col_sep: ",", headers: false)

   c = Customer.new  
   csv.each do |row|
    c.warranty_part_no = row[2],
    c.warranty_part_desc = row[3]
   end
   c.save
  end
end

, RailsApp, rake import:csv_file

, - .

+3

, rails runner Rails Command Line Docs, ruby ​​ script rails.

, .

+1

, config/environment.rb .

+1

, Rails script.

Rails, :

CSV

, CSV .

, "process_csv", CSV Hash - ActiveRecord Mongoid.

./config/initializers/process_csv.rb process_csv, CSV.

: key_mapping, CSV ActiveRecord, CSV- .

:

http://www.unixgods.org/~tilo/Ruby/process_csv_as_hashes.html

:.

require 'process_csv'

File.process_csv( file ) do | hash |
   Consumer.create( hash )
end

!

+1

All Articles