Saturday, May 31, 2008

transaction.records.create!(row.to_hash)

This one I really like:

transactions.records.create!(row.to_hash)

But now I have a problem. Is this where I indicate what table I want my csv file imported to? I used the word transactions and maybe should use a different one not to be confused with the .transaction class method.

Note my table name is plural... Should I use the plural here?

(row.to_hash)

James told me this magic allows me not to have to specify a hash for all my columns that I want to import into my database table. If I did not have this I would have to do this:

transactions.records.create!(:date => date, :amount => amount, :card_id => card_id

If I had a ton of columns this would hard to do... Also James said that in order for this row.to_hash to work you need to have headers set to true or specify the headers in the block or it will complain.

3 comments:

JEG2 said...

I believe you want to use Record.create!(row.to_hash) to load the objects into the database.

Akkdio said...

So how does it know what table in my database to create records in?

If I just used Record.create!(row.to_hash) there is no table mentioned?

JEG2 said...

The Record class wraps the records table in your database. Thus Record.create!(…) builds and saves a new entry in that table.

Just FYI, we're firmly in Rails-land with this question and out of FasterCSV territory. You may want to begin looking into some basic Rails resources.