In my ruby model I have a has_and_belongs_to_many relation with a model "search":
has_and_belongs_to_many :searches
I want to add a new search object only if it does not already exists, so I wrote:
def append_unless_already_there search
unless searches.exists?(search)
searches << search
end
However, adding 2 times a new object passes the condition, and results in a sql exception. Tried replacing search with search.id, but does not change anything. I added some logging to the code:
def append_unless_already_there search
puts ""
puts searches.exists?(search)
unless searches.exists?(search)
puts "["
searches.each do |s|
puts s.id
end
puts "]"
puts search.id
searches << search
end
end
Adding 5 search objects, of which the last 2 are equal, results in the following logging when adding the last object:
false
[
12
5
8
1
]
1
As I read the documentation and examples given, this last exists? check should return true. I cannot figure out what I am missing here. Thanks in advance.