Adds support for :all_or_none option on #import

This commit is contained in:
Gonzalo Rodriguez 2012-05-03 00:20:41 -03:00
parent f74bd2fbbd
commit eac7d5f949
2 changed files with 45 additions and 3 deletions

View file

@ -254,8 +254,12 @@ class ActiveRecord::Base
end end
end end
array_of_attributes.compact! 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) ActiveRecord::Import::Result.new(failed_instances, num_inserts)
end end

View file

@ -65,7 +65,45 @@ describe "#import" do
end end
end end
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 "with :synchronize option" do
context "synchronizing on new records" do context "synchronizing on new records" do
let(:new_topics) { Build(3, :topics) } let(:new_topics) { Build(3, :topics) }