views:

41

answers:

1

Forgive me if I've got my terminology wrong; I am still quite new to Ruby and Rails.

For school I am working on an RoR project as part of a team. I was pair programming with a teammate, who actually happens to be experienced in RoR; and I wrote something like the following:

d = self.deliverables.find_all_by_lifecycle_id(self.lifecycle_id)

My pair programming partner stopped me at this point and explained that this wouldn't work, because find_all_by_lifecycle_id could only be resolved successfully if called by the Deliverable model, which inherits from ActiveRecord::Base (which is, in turn, the class responsible for providing such magical functionality). The self.deliverables method returns an array, which doesn't offer the same capabilities. The alternate solution he suggested was to use a named scope.

I protested: "But... I'm pretty sure I tried it already... and it worked."

Sure enough, it does seem to work, as we discovered when we tested it out just to humor me. What was my teammate missing? I certainly don't have the expertise to see what could've been wrong about what he said (it made sense to me).

+2  A: 

I take it, self.deliverables is defined by :has_many association. In this case, it's not just a simple array. Some of the things you can do with such collection are highlighted in the official rails guide. In particular, check part 4.3.1.10 collection.find(…):
The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find.

It doesn't mention find_by_xxx syntax explicitly, but like you I've found it works in practice.

Nikita Rybak
Very helpful -- thanks!
Dan Tao
`find_by_xxx` comes from the `method_missing` in `ActiveRecord::Base`, which is one of the ancestors of the `has_many` association object.
Swanand
@Swanand I understand the technical side of the trick, I just wish there was some clear documentation about it. Not forcing me to determine the type of "has_many association object" at runtime and then check its sources.
Nikita Rybak