ActiveRecord and Threads

Ryan Daigle
Thu, 25 Aug 2005 14:40:40 -0000

I''m having an issue where code that works in a single threaded model is
throwing a wierd exception when I spawn my own thread.  Here is the code in
question:

relationship = Relationship.new(:src_entity => @entity,
          :created_by => @entity.created_by,
          :target_entity => target_entity,
          :relationship_type => rel_type)

And the error that is thrown is this:

/usr/lib/ruby/gems/1.8/gems/activerecord-1.11.1/lib/active_record/associations/association_proxy.rb:93:in
`raise_on_type_mismatch'': Entity expected, got Entity
(ActiveRecord::AssociationTypeMismatch)
        from
/usr/lib/ruby/gems/1.8/gems/activerecord-1.11.1/lib/active_record/associations/belongs_to_association.rb:25:in
`replace''
        from
/usr/lib/ruby/gems/1.8/gems/activerecord-1.11.1/lib/active_record/associations.rb:628:in
`src_entity=''
        from
/usr/lib/ruby/gems/1.8/gems/activerecord-1.11.1/lib/active_record/associations.rb:621:in
`src_entity=''

As you can see, it expects a class of type "Entity", and it has a
class of type
"Entity" - so I don''t know what the problem is.

Again, this only occurs when I spawn a new thread like so:

indexer = EntityIndexer.new(entity)
Thread.abort_on_exception = true
Thread.new(indexer) do | entity_indexer |
  entity_indexer.index
end

The "entity" argument that''s passed into the new is
what''s available in the
above code snippet as "@entity".

def initialize(entity)
  @entity = entity
end

Can anybody point me in the right direction, I''ve been banging my head
on this
for hours and don''t know enough about ActiveRecord or Ruby threading to
intelligently troubleshoot this.

Any help would be much appreciated.

-Ryan