Array::include? on ActiveRecord collection not calling op== ?

Posted by tribalvibes on Stack Overflow See other posts from Stack Overflow or by tribalvibes
Published on 2010-03-12T03:44:10Z Indexed on 2010/03/12 3:47 UTC
Read the original article Hit count: 255

Filed under:
|
|
|
|

Given a collection of named Foos from ActiveRecord, why does Array.include? not seem to call Foo.== but yet index does?

class Foo < ActiveRecord::Base def ==(s) self.name == s end end

class Bar < ActiveRecord::Base has_many :foos end

bar.foos << Foo.new( :name => 'hmm' )

bar.foos.all.include?('hmm') # does select all from db every time => true

bar.foos.include?('hmm') # does not go to db, but does not find the Foo! => false

bar.foos.index('hmm') # does not go to db, but does find the Foo[0] ! => 0

bar.foos.index('eh') # no such object => nil

I understand shallow about the proxies, but (without a detour into the AR source) why is index seemingly behaving correctly but include? is not !?

Is this a bug in the proxy behavior, and/or is this behavior documented somewhere ?

Thanks.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about rails