Ruby types of collections in ActiveRecord

Posted by kmorris511 on Stack Overflow See other posts from Stack Overflow or by kmorris511
Published on 2009-07-08T17:43:10Z Indexed on 2010/03/23 20:43 UTC
Read the original article Hit count: 454

Filed under:
|

If I have an object with a collection of child objects in ActiveRecord, i.e.

class Foo < ActiveRecord::Base
  has_many :bars, ...
end

and I attempt to run Array's find method against that collection:

foo_instance.bars.find { ... }

I receive:

ActiveRecord::RecordNotFound: Couldn't find Bar without an ID

I assume this is because ActiveRecord has hijacked the find method for its own purposes. Now, I can use detect and everything is fine. However to satisfy my own curiousity, I attempted to use metaprogramming to explicitly steal the find method back for one run:

unbound_method = [].method('find').unbind
unbound_method.bind(foo_instance.bars).call { ... }

and I receive this error:

TypeError: bind argument must be an instance of Array

so clearly Ruby doesn't think foo_instance.bars is an Array and yet:

foo_instance.bars.instance_of?(Array) -> true

Can anybody help me with an explanation of this and of a way to get around it with metaprogramming?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about activerecord