ActiveRecord AssociationTypeMismatch: User expected, got User
May 13, 2008Look familiar? ActiveRecord, fortunately, tells you when you try to assign an object of the wrong class to an association so you'd get this error if you tried to assign a String as the Comment for a Post (which is the correct usage). But sometimes you'll get the error in this case:
1 @comment = @question.comments.build(params[:comment]) 2 @comment.user = current_user # raises "User expected, got User"
Now just earlier today, I got this "User expected, got User" error message and it stumped for me a few minutes. I then realized it's because I changed the User class, which usually isn't a problem since Rails reloads your models in the development environment. But since the Comment class is in a plugin (actsascommentable) and plugins aren't reloaded every request, the Comment class was expecting the User class as-it-was when mongrel was started (and the plugin was loaded).
Sooo.... to save developers between 5 seconds to 5 hours, I added this message to the exception raised (only if the two classes have the same name):
1 (did you change the User class? try restarting mongrel)
I wrote a patch for the changes to add the helpful message. It's super-simple, but hey, I gotta start somewhere. I also made a ticket on the Rails LightHouse project, hopefully it'll get pulled into Rails.
Update: I found this guide on contributing to rails and see that I'm not supposed to fork Rails in GitHub unless its for something big. So I deleted my fork.
Comments
I had this bite me a week ago and being new it screwed with me longer than it should have. Would have been nice to see your version of the exception message.
Great contribution!
This got me last week when doing Merb/AR dev, thanks for the heads up. I was so fed up that I just bypassed the proxy and passed :
Helpful. Thanks for posting this.
Leave a Comment