Not able to import csv to MySQL db in Ruby on Rails 3
mysql, ruby, ruby-on-rails-3
Solution
The problem, as you have figured out, is that your Rails environment isn't loading. You can do this in a standalone script by including your Customer model, active_record, and establishing a connection using your database.yml.
However, there's an easier way. Create a rake task like this:
namespace :data do
desc "Import data from CSV"
task :import => :environment do
#Your script here
end
end
The `=> :environment` tells rake to load Rails so your database connections and all your models will just be there for you to use.
Invoke it with `rake data:import`, adding `RAILS_ENV=production` if you want production environment.
Problem
I am working on importing data from a CSV file into MySQL db through Ruby on Rails 3. The customer model has already been created. Also, the script below will produce puts row[2] and puts row[3] correctly. When I add the assignments for the database fields of customers.warranty_part_no and warranty_part_desc it produces the 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 get. ``` uninitialized constant Customer (NameError) ``` After some testing I think this problem is because I am running this script from command line so the customer.rb model is not being executed with the larger rails app so the Customer class never gets created. How can I run this script from command line and take advantage of ActiveRecord or activerecord-import? If that is not possible, how can I create a route for it or call it from a view in the app? I am on Ruby 1.9.2 and Rails 3.2.2. Thanks in advance for any advice.