Pedro Costa
2007-Jun-18 13:34 UTC
Problem with belongs_to associations validating associated class: bug in rails in development mode?
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. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---