Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Update All in batches
=begin
@conditions, @batch size are created using VALUES hash that is passed
If need to check additional conditions, pass in a where that is prepended before the where using @conditions
Invocation:
update_all_in_batches({ :deleted => false }) { |c| User.where(@conditions).limit(@batch_size).update_all(c) }
=end
def update_all_in_batches(change_hash)
frame_conditions(change_hash)
begin
updated_count = yield(change_hash)
end while updated_count == @batch_size
nil
end
def frame_conditions(change_hash)
# Not sure if we've to exclude created_at, updated_at
@conditions = [[]]
@batch_size = change_hash.delete(:batch_size) || 500
change_hash.each do |key ,value|
if value.nil?
@conditions[0] << "`#{key}` is not null"
else
@conditions[0] << "`#{key}` != ?"
@conditions << value
end
end
@conditions[0] = @conditions[0].join(" and ")
nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.