Nov
12th
Wed
12th
ActiveRecord.connection.execute and INSERT statement gotcha.
Today I was working with a more complex version of the following code using ActiveRecord:
def find_or_create_user_by_id(id)
begin
user = User.find(id)
rescue
User.connection.execute("INSERT INTO users (id ) VALUES(#{id})")
user = User.find(id)
end
return user
end
What’s wrong with this?
The second User.find will throw ActiveRecord::RecordNotFound. The problem is that the execute method, doesn’t invalidate cache, so the second User.find will just hit cache (cache created by the first User.find) instead of hitting the database.
To solve the problem I had to use User.connection.insert, it invalidates cache so the second User.find hits database.
I was hardly able to find any documentation that would describe this behaviour.