Merge pull request #56 from grzuy/support_all_or_none_records

Adds support for :all_or_none option on #import
This commit is contained in:
Zach Dennis 2012-08-29 20:48:18 -07:00
commit 6182b944ef
2 changed files with 45 additions and 3 deletions

View file

@ -260,8 +260,12 @@ class ActiveRecord::Base
end
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

View file

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