Forum: Ruby on Rails Problem with belongs_to associations validating associated c

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Pedro C. (Guest)
on 2007-06-18 17:35
(Received via mailing list)
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 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}"

(this validation is done on association_proxy.rb)

So, to solve this problem you either set the cache_classes to true or
change the
method to not cache the associated class:

  def klass
    active_record.send(:compute_type, class_name)

instead of :

  def klass
    @klass ||= active_record.send(:compute_type, class_name)

Is this a bug in rails?

This topic is locked and can not be replied to.