views:

1090

answers:

3

Hi, 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

+1  A: 

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.

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

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.

mikej
+1  A: 

Use the FasterCSV gem.

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

Jasim