views:

99

answers:

2

I'm currently importing a CSV into an activerecord element but can't choose to parse the elements as say ints or decimals on a case by case basis using fastercsv. I can either choose to parse everything as an int or the other, or all as strings. I need to parse some columns as ints, some as decimals and some as strings.

Otherwise, is there a way after I've parsed everything as strings to convert and update individual elements in the activerecord to the new form? Say parse values in as strings then convert certain values to ints, others to decs, etc?

A: 

Simply supply the data to ActiveRecord as string. ActiveRecord knowns your database schema and knows how to parse the input.

For instance, you don't need to cast a string to integer when you set the value for a foreign key.

r = Record.create :relation_id => "3"
r.relation_id
# => 3
# note the difference between "3" and 3
Simone Carletti
A: 

For general use, Simone's answer is better. That said, if you need to do something with the data (conditional checks, math, etc) before making an active record object, you can supply custom converters for just the fields you need.

For an example, look at the test_convert_with_custom_code_using_field_info method in http://fastercsv.rubyforge.org/svn/trunk/test/tc_data_converters.rb

Ckhrysze