Skip to content

Commit

Permalink
Merge pull request #448 from jkowens/load_assocation_ids
Browse files Browse the repository at this point in the history
Sync belongs_to association id before importing
  • Loading branch information
jkowens committed Sep 10, 2017
2 parents c38ac0d + f03460d commit 7e7cd68
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/activerecord-import/import.rb
Expand Up @@ -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) ||
Expand Down Expand Up @@ -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:
Expand Down
13 changes: 13 additions & 0 deletions test/support/shared_examples/recursive_import.rb
Expand Up @@ -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
Expand Down

0 comments on commit 7e7cd68

Please sign in to comment.