From e12f9c4951b5e93e01ad60b0fd92f45eb3482e87 Mon Sep 17 00:00:00 2001 From: Jared Luxenberg Date: Sat, 4 Aug 2012 17:31:56 -0700 Subject: [PATCH] Model#import fails to find model's primary key sequence Fixes a bug where Model#import does not work when a model's primary key has no associated 'sequence' in the database. If a value for the primary key is specified, then the insert should not require a database 'sequence' to generate a value for that primary key field. --- lib/activerecord-import/import.rb | 2 +- test/postgresql/import_test.rb | 5 +++++ test/schema/generic_schema.rb | 4 ++++ test/support/factories.rb | 6 +++++- 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/activerecord-import/import.rb b/lib/activerecord-import/import.rb index f32e64b..c18dad8 100644 --- a/lib/activerecord-import/import.rb +++ b/lib/activerecord-import/import.rb @@ -297,7 +297,7 @@ class ActiveRecord::Base array_of_attributes.map do |arr| my_values = arr.each_with_index.map do |val,j| column = columns[j] - if !sequence_name.blank? && column.name == primary_key && val.nil? + if val.nil? && !sequence_name.blank? && column.name == primary_key connection.next_value_for_sequence(sequence_name) else connection.quote(column.type_cast(val), column) diff --git a/test/postgresql/import_test.rb b/test/postgresql/import_test.rb index 45e97ef..0dec7e3 100644 --- a/test/postgresql/import_test.rb +++ b/test/postgresql/import_test.rb @@ -17,4 +17,9 @@ describe "#import" do assert_equal 1, result.num_inserts end end + + it "should import models whose primary key has no sequence if the primary key's value is specified" do + result = Widget.import Build(3, :widgets) + assert_equal 1, result.num_inserts + end end diff --git a/test/schema/generic_schema.rb b/test/schema/generic_schema.rb index 02bd23e..af7a0af 100644 --- a/test/schema/generic_schema.rb +++ b/test/schema/generic_schema.rb @@ -95,4 +95,8 @@ ActiveRecord::Schema.define do end add_index :animals, [:name], :unique => true, :name => 'uk_animals' + + create_table :widgets, :id => false, :force => true do |t| + t.integer :w_id + end end diff --git a/test/support/factories.rb b/test/support/factories.rb index a7b737a..34d83e8 100644 --- a/test/support/factories.rb +++ b/test/support/factories.rb @@ -10,4 +10,8 @@ end Factory.define :topic do |m| m.sequence(:title){ |n| "Title #{n}"} m.sequence(:author_name){ |n| "Author #{n}"} -end \ No newline at end of file +end + +Factory.define :widget do |m| + m.sequence(:w_id){ |n| n} +end