2

I have created Rails database using the following schema:

ActiveRecord::Schema.define(:version => 20090807141407) do

  create_table "trunks", :force => true do |t|
    t.integer  "npa"
    t.integer  "nxxFrom"
    t.integer  "nxxTo"
    t.string   "trnk"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

In my CSV file, I only have the first four columns (npa, nxxFrom, nxxTo, and trnk).

How can I import the CSV data while also updating the last two columns?

Thanks always

2
  • If you create an ActiveRecord model from each line in the CSV file and save it then ActiveRecord will populate created_at/updated_at for you. Are you asking how to do CSV parsing in Ruby? Commented Aug 7, 2009 at 14:30
  • Sorry I am a newbie. The CSV file is a raw data from a server. Are you saying I can somehow convert that into an ActiveRecord model? If that's possible, it would be great Commented Aug 7, 2009 at 14:34

3 Answers 3

2

To use the csv module which is part of the standard Ruby library:

require 'csv'

# row will be an array with the fields in the order they appear in the file
CSV.open('myfile.csv', 'r') do |row|
  # assuming the fields in the CSV file are in order npa, nxxFrom, nxxTo, trnk
  # create and save a Trunk model for each row
  Trunk.create!(:npa => row[0], :nxxFrom => row[1], :nxxTo => row[2], :trnk => row[3])
end

I haven't used fastercsv but looking at its documentation the approach seems the same.

Sign up to request clarification or add additional context in comments.

Comments

2

Use the FasterCSV gem.

A nice example is at http://espndev.com/blog/csv-imports-using-fastercsv/

Comments

1

The last two columns will be updated by ActiveRecord. If they exist in the schema then ActiveRecord will add a value for the created_at and updated_at upon creation of the object. Any modifications to the object will cause the updated_at column to be auto updated.

So when importing from a CSV just map the first 4 columns and save the object. When you retrieve the object you will see the other two values have also been set automatically.

3 Comments

Ok, do I import the data through sqlite3 command utility? Or is there a Rails method that handles this? Thanks for your help!
To import from a CSV there are gems for that. Try fastercsv. (fastercsv.rubyforge.org)
sweet! You guys are the best!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.