# Problem with belongs\_to associations validating associated c

**URL:** <https://www.ruby-forum.com/t/problem-with-belongs-to-associations-validating-associated-c/107139>\
**Category:** Rails\
**Created:** [June 18, 2007, 3:35pm UTC](https://www.ruby-forum.com/t/problem-with-belongs-to-associations-validating-associated-c/107139 "2007-06-18T15:35:08Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jotape](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/c77e96/32.png) [@jotape](https://www.ruby-forum.com/u/jotape)\
**Post date:** [June 18, 2007, 3:35pm UTC](https://www.ruby-forum.com/t/problem-with-belongs-to-associations-validating-associated-c/107139/1 "2007-06-18T15:35:08Z")

</div>

Hi all,

I’m using rails version 1.2.3.

I have the following association in my View class

belongs\_to :viewer, :class\_name =\> ‘User’, :foreign\_key =\> :viewer\_id

And of course i have a User model class defined to.

The problem was that when i tried to use this association it would  
only work once.

At the second try, i would get the following strange error:

ActiveRecord::AssociationTypeMismatch : User expected, got User

On a call to:

my\_view.viewer = my\_user

After a little investigation i found that the problem was related to  
this option in the environments/development.rb

config.cache\_classes = false

If I changed this option to true, everything would work ok. The  
problem is that the associated proxy is caching the associated class,  
and if the previous option is set to false on the second request, the  
User.class.id will be different from the cached user class object  
resulting that the following rails validation will fail:

unless record.is\_a?(@reflection.klass)  
raise ActiveRecord::AssociationTypeMismatch,  
“#{@reflection.class\_name} expected, got #{record.class}”  
end

(this validation is done on association\_proxy.rb)

So, to solve this problem you either set the cache\_classes to true or  
change the  
@reflection.klass  
method to not cache the associated class:

def klass  
active\_record.send(:compute\_type, class\_name)  
end

instead of :

def klass  
@klass ||= active\_record.send(:compute\_type, class\_name)  
end

Is this a bug in rails?

Pedro.
