Rails: class' id / object_id changes during same request
I have been having a problem when I try to compare two Rails models. They should evaluate as the same, but the way ActiveRecord implements == is causing it to fail. What's even stranger is the unit tests are passing.
Suppose a User has many Posts, and Posts has many Comments. User also has_many comments.
(and this is comparing two objects, which should be the same)
User.first.comments.first == Post.forst.comments.first
When I write out the object_ids to Rails.logger, they are not equal.开发者_高级运维 After digging through the source code, I've found this condition makes it fail.
http://github.com/rails/rails/blob/30dcac292606da0e031d1e0dfbb6fc6109e5da60/activerecord/lib/active_record/base.rb#L1602
I expect:
User.first.comments.class.object_id == Post.first.comments.class.object_id
But this is not the case.
The model includes a module, which does the following inside self.included(base)
base.send :include, InstanceMethods
base.send :extend, ClassMethods
When I take the include out of the models, everything works fine.
Is there something with the include/extend pattern that is causing the models to reload or not be cached correctly within the same request?
Any ideas here would be great!!!
object_id is the ruby id for the instance not the id of the row in your database. The ActiveRecord override of == compares id and not object_id.
精彩评论