find_by_id 等如何在 ActiveRecord 数组上工作?

发布于 2024-09-26 10:27:17 字数 633 浏览 3 评论 0原文

如果我的术语有误,请原谅我;我对 Ruby 和 Rails 还很陌生。

在学校,我作为团队的一员参与 RoR 项目。我和一个队友结对编程,他实际上在 RoR 方面很有经验;我写了如下内容:

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

我的结对编程伙伴此时阻止了我,并解释说这是行不通的,因为 find_all_by_lifecycle_id 只有在被 Deliverable 调用时才能成功解析code> 模型,它继承自 ActiveRecord::Base (反过来,该类负责提供这种神奇的功能)。 self.deliverables 方法返回一个数组,但它不提供相同的功能。他建议的替代解决方案是使用命名范围

我抗议道:“但是……我很确定我已经尝试过了......而且它有效。”

果然,它似乎确实有效,正如我们在测试它时发现的那样,只是为了逗我开心。我的队友错过了什么?我当然没有专业知识来判断他所说的话可能有什么问题(这对我来说是有道理的)。

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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海螺姑娘 2024-10-03 10:27:17

我认为, self.deliverables 是由 :has_many 关联定义的。在这种情况下,它不仅仅是一个简单的数组。 官方 Rails 指南。特别是,请检查4.3.1.10 collection.find(…)部分:
collection.find 方法查找集合中的对象。它使用与 ActiveRecord::Base.find 相同的语法和选项。

它没有明确提及 find_by_xxx 语法,但像您一样,我发现它在实践中有效。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文