Adds support for :all_or_none option on #import
This commit is contained in:
parent
f74bd2fbbd
commit
eac7d5f949
|
@ -255,7 +255,11 @@ class ActiveRecord::Base
|
|||
end
|
||||
array_of_attributes.compact!
|
||||
|
||||
num_inserts = array_of_attributes.empty? ? 0 : import_without_validations_or_callbacks( column_names, array_of_attributes, options )
|
||||
num_inserts = if array_of_attributes.empty? || options[:all_or_none] && failed_instances.any?
|
||||
0
|
||||
else
|
||||
import_without_validations_or_callbacks( column_names, array_of_attributes, options )
|
||||
end
|
||||
ActiveRecord::Import::Result.new(failed_instances, num_inserts)
|
||||
end
|
||||
|
||||
|
|
|
@ -66,6 +66,44 @@ describe "#import" do
|
|||
end
|
||||
end
|
||||
|
||||
context "with :all_or_none option" do
|
||||
let(:columns) { %w(title author_name) }
|
||||
let(:valid_values) { [[ "LDAP", "Jerry Carter"], ["Rails Recipes", "Chad Fowler"]] }
|
||||
let(:invalid_values) { [[ "The RSpec Book", ""], ["Agile+UX", ""]] }
|
||||
let(:mixed_values) { valid_values + invalid_values }
|
||||
|
||||
context "with validation checks turned on" do
|
||||
it "should import valid data" do
|
||||
assert_difference "Topic.count", +2 do
|
||||
result = Topic.import columns, valid_values, :all_or_none => true
|
||||
end
|
||||
end
|
||||
|
||||
it "should not import invalid data" do
|
||||
assert_no_difference "Topic.count" do
|
||||
result = Topic.import columns, invalid_values, :all_or_none => true
|
||||
end
|
||||
end
|
||||
|
||||
it "should not import valid data when mixed with invalid data" do
|
||||
assert_no_difference "Topic.count" do
|
||||
result = Topic.import columns, mixed_values, :all_or_none => true
|
||||
end
|
||||
end
|
||||
|
||||
it "should report the failed instances" do
|
||||
results = Topic.import columns, mixed_values, :all_or_none => true
|
||||
assert_equal invalid_values.size, results.failed_instances.size
|
||||
results.failed_instances.each { |e| assert_kind_of Topic, e }
|
||||
end
|
||||
|
||||
it "should report the zero inserts" do
|
||||
results = Topic.import columns, mixed_values, :all_or_none => true
|
||||
assert_equal 0, results.num_inserts
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context "with :synchronize option" do
|
||||
context "synchronizing on new records" do
|
||||
let(:new_topics) { Build(3, :topics) }
|
||||
|
|
Loading…
Reference in a new issue