diff --git a/lib/activerecord-import/import.rb b/lib/activerecord-import/import.rb index 0646c1f..a914934 100644 --- a/lib/activerecord-import/import.rb +++ b/lib/activerecord-import/import.rb @@ -137,8 +137,8 @@ class ActiveRecord::Base # # # Example synchronizing unsaved/new instances in memory by using a uniqued imported field # posts = [BlogPost.new(:title => "Foo"), BlogPost.new(:title => "Bar")] - # BlogPost.import posts, :synchronize => posts - # puts posts.first.new_record? # => false + # BlogPost.import posts, :synchronize => posts, :synchronize_keys => [:title] + # puts posts.first.persisted? # => true # # == On Duplicate Key Update (MySQL only) # diff --git a/lib/activerecord-import/synchronize.rb b/lib/activerecord-import/synchronize.rb index 60408e5..a5286d7 100644 --- a/lib/activerecord-import/synchronize.rb +++ b/lib/activerecord-import/synchronize.rb @@ -43,6 +43,10 @@ module ActiveRecord # :nodoc: instance.clear_aggregation_cache instance.clear_association_cache instance.instance_variable_set '@attributes', matched_instance.attributes + # Since the instance now accurately reflects the record in + # the database, ensure that instance.persisted? is true. + instance.instance_variable_set '@new_record', false + instance.instance_variable_set '@destroyed', false end end end @@ -52,4 +56,4 @@ module ActiveRecord # :nodoc: self.class.synchronize(instances, key) end end -end \ No newline at end of file +end diff --git a/test/import_test.rb b/test/import_test.rb index efc1ee9..cc06891 100644 --- a/test/import_test.rb +++ b/test/import_test.rb @@ -134,8 +134,18 @@ describe "#import" do let(:new_topics) { Build(3, :topics) } it "reloads data for existing in-memory instances" do - Topic.import(new_topics, :synchronize => new_topics, :synchronize_key => [:title] ) - assert new_topics.all?(&:new_record?), "Records should have been reloaded" + Topic.import(new_topics, :synchronize => new_topics, :synchronize_keys => [:title] ) + assert new_topics.all?(&:persisted?), "Records should have been reloaded" + end + end + + context "synchronizing on destroyed records with explicit conditions" do + let(:new_topics) { Generate(3, :topics) } + + it "reloads data for existing in-memory instances" do + new_topics.each &:destroy + Topic.import(new_topics, :synchronize => new_topics, :synchronize_keys => [:title] ) + assert new_topics.all?(&:persisted?), "Records should have been reloaded" end end end