0

I have a collection of characters in following. Each character has a unique handle. I've checked the database to make sure there is only one character with the handle barry1. I'm trying to do:

following.include?(other_character)   # false

It's returning false, but I'm sure that barry1 is in following. It thinks the ids are different, but there's only one barry1. What's going on?

character.rb

has_many :following, through: :active_follow_relationships,  source: :followed

puts:

puts following.first.handle    # barry1
puts other_character.handle    # barry1

puts following.first     # #<Character:0x007fef15231490>
puts other_character     # #<Character:0x007fef09bb4d58>

puts following.first.id    # 21
puts other_character.id    # 8
Bazley
  • 2,699
  • 5
  • 36
  • 61

1 Answers1

0

it seems that actually at least two different characters have the handle attribute with the value barry1. (cf ids 21 and 8). They are both persisted in a different place in memory and thus have two distinct ids.

If you want to check however that the collection following contains at least one characters with the handle attribute equal to barry1 this should work:

following.pluck(:handle).include? other_character.handle

leonard
  • 1
  • 1
  • This is going to work fine but if he wants to use `following` later on, after check, rails will create two queries (first for plucking only the `:handle` column, second for `following` objects) – Krzysztof Witczak Sep 26 '17 at 19:33
  • In the console `Character.find_by(handle: 'barry1')` only returns a single record. How is it possible for there to be a single record in the database but two records in memory? – Bazley Sep 26 '17 at 22:14
  • 1
    That's because memory object is only representation of database object, you can create multiple variables (instances) of the same DB row and they won't be placed in the same memory spot. Check this: https://stackoverflow.com/questions/4738439/how-to-test-for-activerecord-object-equality – Krzysztof Witczak Sep 27 '17 at 09:51
  • Indeed, the `find_by` method will return the first object that matches your search. You should check if it's the only one with : `Character.where(handle :'barry1')` – leonard Sep 28 '17 at 16:13