Skip to content

Commit

Permalink
Fix importing STI models with ActiveRecord 6
Browse files Browse the repository at this point in the history
  • Loading branch information
jkowens committed Jul 15, 2021
1 parent be396d0 commit 737638c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
15 changes: 8 additions & 7 deletions lib/activerecord-import/import.rb
Original file line number Diff line number Diff line change
Expand Up @@ -775,21 +775,22 @@ def import_without_validations_or_callbacks( column_names, array_of_attributes,
unless scope_columns.blank?
scope_columns.zip(scope_values).each do |name, value|
name_as_sym = name.to_sym
next if column_names.include?(name_as_sym)

is_sti = (name_as_sym == inheritance_column.to_sym && self < base_class)
value = Array(value).first if is_sti

next if column_names.include?(name_as_sym) || name_as_sym == inheritance_column.to_sym
column_names << name_as_sym
array_of_attributes.each { |attrs| attrs << value }
end
end

if finder_needs_type_condition?
unless column_names.include?(inheritance_column.to_sym)
column_names << inheritance_column.to_sym
array_of_attributes.each { |attrs| attrs << sti_name }
end
end

columns = column_names.each_with_index.map do |name, i|
column = columns_hash[name.to_s]

raise ActiveRecord::Import::MissingColumnError.new(name.to_s, i) if column.nil?

column
end

Expand Down
12 changes: 11 additions & 1 deletion test/import_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,17 @@
assert_difference "Dictionary.count", +1 do
Dictionary.import dictionaries
end
assert_equal "Dictionary", Dictionary.first.type
assert_equal "Dictionary", Dictionary.last.type
end

it "should import arrays successfully" do
columns = [:author_name, :title]
values = [["Noah Webster", "Webster's Dictionary"]]

assert_difference "Dictionary.count", +1 do
Dictionary.import columns, values
end
assert_equal "Dictionary", Dictionary.last.type
end
end

Expand Down
1 change: 1 addition & 0 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'pathname'
require 'rake'
test_dir = Pathname.new File.dirname(__FILE__)
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
Expand Down

0 comments on commit 737638c

Please sign in to comment.