显示RoR关系

发布于 2024-09-16 03:32:01 字数 277 浏览 6 评论 0原文

我已经设置了一个模型关系,当我使用类似于以下的代码时,一切都运行良好:

@parent.child.each do |item|
item.name
end

但是我如何调用给定的特定孩子,

例如。

儿童 ID 为 14

希望拨打以下电话:

@parent.child[childid].name #>>>>>> CHILD'S NAME

I have setup a model relationship and all is working well when I use code similar to:

@parent.child.each do |item|
item.name
end

But how would I call just a specific child given there id

eg.

Child ID is 14

Would like a call like:

@parent.child[childid].name #>>>>>> CHILD'S NAME

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

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

发布评论

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

评论(2

守望孤独 2024-09-23 03:32:01

尝试:

@parent.children.detect { |child| child.id == 14 }

这应该返回对象而不查询数据库。然后您可以对其调用 .name 方法。

Try:

@parent.children.detect { |child| child.id == 14 }

This should return the object without querying the database. You can then call the .name method on it.

你列表最软的妹 2024-09-23 03:32:01

@parent.child[14] 很可能无法正常工作,child 是一个数组,如果它是一个 has_many 关系,但是该数组索引与子项的 id 不同。所以你可以这样做:

@parent.child.find(14).name

我不太确定,但如果你这样做:

@parent = Parent.find(some_id, :include => :child)
@parent.child.find(some_other_id) # should hit the query cache

@parent.child[14] would most likely not work correctly, child is an array, if it is a has_many relation, but the array index is not the same as the id of the child. so you can do something like this:

@parent.child.find(14).name

I'm not really sure, but if you do something like this:

@parent = Parent.find(some_id, :include => :child)
@parent.child.find(some_other_id) # should hit the query cache
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文