Rather, your database software may
have a mechanism to import CSV data directly. This will result in a much faster import, and if
you know the data is well formed, the benefits of using Active Record as an intermediary may
not be necessary.
CHAPTER 7 ?– WORKING WITH LEGACY SCHEMA 185
Using your database mechanism for CSV importing aside, there are several benefits to
writing a program using Active Record to import your CSV data. You can use Active Record validations
to verify the validity of your CSV data, and either address the issues in your program
or exclude those records. In addition, if you know you need to do data manipulations, such
as concatenating and modifying fields in the CSV, it can be very effective to write a Ruby program
to do this import.
In the following code snippet, we read in a CSV file to import into our accounts data that
contains a first name and a last name column:
CSV::Reader.parse(File.open('accounts.csv', 'rb')) do |row|
Account.create(:last_name => row[0], :first_name => row[1])
end
If any one of the records that are being imported fail validations, it will not be created.
Pages:
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423