Permalink
Browse files

Merge pull request #448 from jkowens/load_assocation_ids

Sync belongs_to association id before importing
  • Loading branch information...
jkowens committed Sep 10, 2017
2 parents c38ac0d + f03460d commit 7e7cd68ccff6fd22294ffd915c0bbfd22420eaaf
Showing with 29 additions and 0 deletions.
  1. +16 −0 lib/activerecord-import/import.rb
  2. +13 −0 test/support/shared_examples/recursive_import.rb
@@ -446,6 +446,10 @@ def import_helper( *args )
end
array_of_attributes = models.map do |model|
if support_setting_primary_key_of_imported_objects?
load_association_ids(model)
end
column_names.map do |name|
if stored_attrs.key?(name.to_sym) ||
serialized_attrs.key?(name) ||
@@ -698,6 +702,18 @@ def set_attributes_and_mark_clean(models, import_result, timestamps, options)
end
end
# Sync belongs_to association ids with foreign key field
def load_association_ids(model)
association_reflections = model.class.reflect_on_all_associations(:belongs_to)
association_reflections.each do |association_reflection|
association = model.association(association_reflection.name)
association = association.target
if association && association.id
model.public_send("#{association_reflection.foreign_key}=", association.id)
end
end
end
def import_associations(models, options)
# now, for all the dirty associations, collect them into a new set of models, then recurse.
# notes:
@@ -102,6 +102,19 @@ def should_support_recursive_import
end
end
it "imports an imported belongs_to association id" do
books = new_topics[0].books.to_a
Topic.import new_topics, validate: false
assert_difference "Book.count", books.size do
Book.import books, validate: false
end
books.each do |book|
assert_not_nil book.topic_id
end
end
unless ENV["SKIP_COMPOSITE_PK"]
describe "with composite primary keys" do
it "should import models and set id" do

0 comments on commit 7e7cd68

Please sign in to comment.