Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails models reloaded mid-request resulting in AssociationTypeMismatch

We've been running into a problem in Rails 3.1 when we run in development mode. It seems that our models sometimes get reloaded mid request, and a new object_id is set on our model's classes. Which then results in an ActiveRecord::AssociationTypeMismatch

ActiveRecord::AssociationTypeMismatch Character(#2194222580) expected, got Character(#2185863000)

If we turn config.cache_classes = true in development.rb the problem seems to go away, but it's unrealistic to develop like that as we'll have to constantly be restarting our servers.

Anybody have an idea why models may be reloaded mid request, or if there is a way we could force the cache to last through the entire request?

like image 899
aproctor Avatar asked Jan 31 '12 16:01

aproctor


1 Answers

With config.cache_classes = false, any change to the model causes a reload. This includes defining/redefining a constant defined in/known to the model.

We had this problem using rspec and ActsAsFu. Redefining the Fu class during the test caused related (even indirectly related) classes to reload, and we got the ActiveRecord::AssociationTypeMismatch error on the related object. We figured this our because we had tests that ran fine alone, but failed when running after other tests. Our solution was to just create separately-named Fu classes for each configuration, and avoid reassigning the class name during the test.

So my recommendation is to make sure you are not redefining any constants known to your Character class (or known to classes known to your Character class, etc.)

like image 72
Tom Wilson Avatar answered Oct 06 '22 18:10

Tom Wilson