I have an event model that has a has_and_belongs_to_many :users, inverse_of: nil
.
When I look at the event, I can see the user:
event.users.first
# => #<User _id: BSON::ObjectId('554daa95656c790b0e140000'), authentication_token: "U8wsVzXoPKfQ26TkZHSs", deleted_at: nil, email: "michael.jordan@nba.com", event_id: nil, first_name: "Michael", last_name: "Jordan", role_ids: [BSON::ObjectId('54d79542656c795581010000'), BSON::ObjectId('554dab81656c790b0e160000'), BSON::ObjectId('554db900656c790b0e1a0000')]>
I also loaded the user, and looked at her data:
user.first
# => #<User _id: BSON::ObjectId('554daa95656c790b0e140000'), authentication_token: "U8wsVzXoPKfQ26TkZHSs", deleted_at: nil, email: "michael.jordan@nba.com", event_id: nil, first_name: "Michael", last_name: "Jordan", role_ids: [BSON::ObjectId('54d79542656c795581010000'), BSON::ObjectId('554dab81656c790b0e160000'), BSON::ObjectId('554db900656c790b0e1a0000')]>
From what I see so far, I would say they are equal. But when I want to compare them with ==
, they are not equal:
event.users.first == user.first
# => false
I thought this may be because the object_id
values are not the same:
event.users.first.object_id
# => 46965723447420
user.first.object_id
# => 46965766138560
I was not sure about how to analyse further. I simply extracted the user twice:
user1 = User.find("554daa95656c790b0e140000")
# => #<User _id: BSON::ObjectId('554daa95656c790b0e140000'), authentication_token: "U8wsVzXoPKfQ26TkZHSs", deleted_at: nil, email: "michael.jordan@nba.com", event_id: nil, first_name: "Michael", last_name: "Jordan", role_ids: [BSON::ObjectId('54d79542656c795581010000'), BSON::ObjectId('554dab81656c790b0e160000'), BSON::ObjectId('554db900656c790b0e1a0000')]>
user2 = User.find("554daa95656c790b0e140000")
# => #<User _id: BSON::ObjectId('554daa95656c790b0e140000'), authentication_token: "U8wsVzXoPKfQ26TkZHSs", deleted_at: nil, email: "michael.jordan@nba.com", event_id: nil, first_name: "Michael", last_name: "Jordan", role_ids: [BSON::ObjectId('54d79542656c795581010000'), BSON::ObjectId('554dab81656c790b0e160000'), BSON::ObjectId('554db900656c790b0e1a0000')]>
These two users compare to true
with the ==
method:
user1 == user2
# => true
The object_id
values are not the same:
user1.object_id
# => 46965753578080
user2.object_id
# => 46965753704780
Can someone help me understand why the ==
returns false
in the first example but true
in the second example?