weird foreign key constraint failure in transaction

I have an ActiveRecord transaction that works some times and fails some times. I've narrowed it down to where the failure depends on the inclusion of an empty method from a library object. By 'empty', I mean I've removed all code from the method, so the problem is related to making the method call (i.e. it's not in my code). Here's some pseudo code.

def myMethod ClassA.transaction do    # saving class B obj succeeds when this next method is commented out,    # but it fails with 'update violates foreign key constraint' when this method is called    MyLibraryClass.donothing    @objectOfClassA.save!    @objectOfClassB.refToA = objectOfClassA.id

I assume this should read @objectOfClassB.refToA = @objectOfClassA.id

   @objectOfClassB.save! end end

It behaves as if the second save cannot see the object created in the first save, even though they both happen within the transaction.

Why would the inclusion of the unrelated, empty method 'donothing' have such an effect?

Because saying MyLibraryClass means const_missing is hit, triggering the load of my_library_class.rb which contains something funny? (if true then just putting MyLibraryClass in your method (ie call no method on it at all) will also trigger the error you are seeing).

Fred

Frederick Cheung wrote:

ClassA.transaction do    # saving class B obj succeeds when this next method is commented out,    # but it fails with 'update violates foreign key constraint' when this method is called    MyLibraryClass.donothing    @objectOfClassA.save!    @objectOfClassB.refToA = objectOfClassA.id

I assume this should read @objectOfClassB.refToA = @objectOfClassA.id

yes, that's how it should have read.

such an effect?

Because saying MyLibraryClass means const_missing is hit, triggering the load of my_library_class.rb which contains something funny? (if true then just putting MyLibraryClass in your method (ie call no method on it at all) will also trigger the error you are seeing).

You're correct. The error is triggered even with no method call. But even weirder, I moved the MyLibraryClass statement outside of the transaction entirely and it still triggered the error.

However, your message helped: you got me wondering what was in the library class and I found that another developer had added this: require File.dirname(__FILE__) + '/../config/environment'

and that turns out to be causing a problem. I can't explain why that would cause the observed behavior, but at least it's fixed. Thanks.