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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Df7f2bd7326462d28fac369297e5c40d?d=identicon&s=25 Pedro Costa (Guest)
on 2007-06-18 15: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
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.
This topic is locked and can not be replied to.