Here’s the erroneous code snippet.
transaction do
Person.having_email(some_email).find_each(:conditions => ["people.identifier != ? OR people.identifier IS NULL", identifier]) do |person|
if person.identifier?
raise "Person is associated with a different identifier"
else
duplicate_entry = Person.find_by_identifier_and_company_id(identifier, person.company_id)
person.update_attribute(:identifier, identifier) if duplicate_entry.nil?
end
end
end
having_email is a named_scope defined for the Person class.
The issue that I’m facing is that the expression that finds a possible duplicate entry always seems to be returning nil even when a valid record is present in the db. When I evaluate the same expression using the RubyMine debugger, it returns the correct object.
On further introspection, it seems that rails is not firing any query on the duplicate_entry evaluation statement(there is no such query in the logs). On replacing the find_each call with a normal find(:all, ...).each call, things seem to work fine(The duplicate entry retrieval query is present in the logs as well).
I haven’t been able to get my head around what might be causing this. Any ideas?
The root cause of this issue has been explained quite well along with a valid workaround in this blog post