Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validate using given models instead of re-initializing ones #118

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion lib/activerecord-import/import.rb
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,25 @@ def import( *args )
end

return_obj = if is_validating
import_with_validations( column_names, array_of_attributes, options )
if models
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love the idea @giladas, I was thinking about submitting a pull request for exactly this a few days ago.

Since this is more or less the same validation logic as in import_with_validations, perhaps there is a way we can DRY the logic up?

failed_instances = [] ; valid = []
models.each_with_index do |model, index|
if model.valid?
valid << array_of_attributes[index]
else
failed_instances << model
end
end

num_inserts = if valid.empty? || options[:all_or_none] && failed_instances.any?
0
else
import_without_validations_or_callbacks( column_names, valid, options )
end
ActiveRecord::Import::Result.new(failed_instances, num_inserts)
else
import_with_validations( column_names, array_of_attributes, options )
end
else
num_inserts = import_without_validations_or_callbacks( column_names, array_of_attributes, options )
ActiveRecord::Import::Result.new([], num_inserts)
Expand Down