From 8fbf841fde4698f9c915a1928d88799ec8cdad18 Mon Sep 17 00:00:00 2001 From: Zach Dennis Date: Wed, 5 Jan 2011 19:05:31 -0500 Subject: [PATCH] Use ActiveRecord Column#type_cast to properly parse fields represented by a string. Fixed issued reported by Nick Burdick where imported datetime fields was not correctly working with certain string formats for MySQL which doesn't support MM/DD/YYYY format directly. --- lib/activerecord-import/adapters/abstract_adapter.rb | 3 ++- lib/activerecord-import/import.rb | 2 +- test/import_test.rb | 12 ++++++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/activerecord-import/adapters/abstract_adapter.rb b/lib/activerecord-import/adapters/abstract_adapter.rb index f95d5b6..79022f1 100644 --- a/lib/activerecord-import/adapters/abstract_adapter.rb +++ b/lib/activerecord-import/adapters/abstract_adapter.rb @@ -129,7 +129,8 @@ module ActiveRecord::Import::AbstractAdapter array_of_attributes.each do |arr| my_values = [] arr.each_with_index do |val,j| - my_values << quote( val, columns[j] ) + importable_value = columns[j].type_cast(val) + my_values << quote(importable_value, columns[j] ) end values << my_values end diff --git a/lib/activerecord-import/import.rb b/lib/activerecord-import/import.rb index 5e8354c..772166b 100644 --- a/lib/activerecord-import/import.rb +++ b/lib/activerecord-import/import.rb @@ -257,7 +257,7 @@ class ActiveRecord::Base def import_without_validations_or_callbacks( column_names, array_of_attributes, options={} ) escaped_column_names = quote_column_names( column_names ) columns = [] - array_of_attributes.first.each_with_index { |arr,i| columns << columns_hash[ column_names[i] ] } + array_of_attributes.first.each_with_index { |arr,i| columns << columns_hash[ column_names[i].to_s ] } if not supports_import? columns_sql = "(" + escaped_column_names.join( ',' ) + ")" diff --git a/test/import_test.rb b/test/import_test.rb index 317c584..8e0962d 100644 --- a/test/import_test.rb +++ b/test/import_test.rb @@ -199,4 +199,16 @@ describe "#import" do end end + context "importing a datetime field" do + it "should import a date with MM/DD/YYYY format just fine" do + Topic.import [:author_name, :title, :last_read], [["Bob Jones", "Topic 1", "05/14/2010"]] + assert_equal "05/14/2010".to_date, Topic.last.last_read.to_date + end + + it "should import a date with YYYY/MM/DD format just fine" do + Topic.import [:author_name, :title, :last_read], [["Bob Jones", "Topic 2", "2010/05/14"]] + assert_equal "05/14/2010".to_date, Topic.last.last_read.to_date + end + end + end \ No newline at end of file