ActiveRecord pitfall that could cause a disaster

contracts = scope1 + scope2
contracts.each do |contract|
...
end
contracts = scope1.union(scope2)
contracts.find_each do |contract|
...
end
Contract.none.union([]).count
# => 0
Contract.none.union([]).count
# => <number of all contracts>
Contract.none.union([]).to_sql=> "SELECT \"contracts\".* FROM ( (SELECT \"contracts\".* FROM \"contracts\" WHERE (1=0)) UNION (SELECT \"contracts\".* FROM \"contracts\") ) \"contracts\""
@klass.where(relation_or_where_arg, *args)
# If the condition is any blank-ish object, then #where is a no-op and returns
# the current relation.
def where(*args)
if args.empty?
WhereChain.new(spawn)
elsif args.length == 1 && args.first.blank?
self
else
spawn.where!(*args)
end
end

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store