In case anyone likes to import .csv files, or you need to do some single
table exports through csv and then re-import them later on, you can use
the following code I created.

The first file is the rake file and the second file is the lib file.
The command to use is:

rake import_csv_file["somefile.csv"',"some_model"]

Make sure that the header rows of the CSV files you import are the names
of the fields.  So, if you had a table with the following fields:

user_id, name, email, etc.

You would want the csv file to have user_id, name, email, etc. in the
first row cells.  The lib class will automatically singularize and
constantize the model argument passed to the rake task and convert it
for you.  So if you have a model called UserFile you would pass
user_file and it would automatically convert it to UserFile when
preceeding to upload it to the table.

I created an import folder in my rails root for importing the files,
since in this particular case, I'm the only one that's importing.  You
could expand upon this and alter the class to accept file uploads, etc.

Anyhoo, in case someone needs something quick and to the point, here it
is.

Enjoy.

-------------------
RAKE File:

=> tasks/import_csv.rake

desc "Import a CSV using import_csv_file['file.csv','model']"
task :import_csv_file, :file, :model, :needs => :environment do |t,
args|

  p "Starting to import CSV data from #{args.file}."
  parse = ImportCsv.new("#{Rails.root}/import/#{args.file}",
"#{args.model}")
  parse.import
  p "Completed import successfully."

end

RUBY lib file:

=> libs/import_csv.rb

class ImportCsv

  attr_accessor :file, :model

  def initialize(file,model)
    @file = file
    @model = model
  end

  require 'csv'
  def import
    csv_text = File.read(@file)
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
      row = row.to_hash.with_indifferent_access
      
@model.singularize.camelize.constantize.create!(row.to_hash.symbolize_keys)
    end
  end

end

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to