开发者

How is it that find_by_id, etc. work on an ActiveRecord array?

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 m开发者_如何学运维agical 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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜