如何通过 Rails3 中的 has_one 关联找到孩子的父母?

发布于 2024-10-09 01:07:45 字数 569 浏览 7 评论 0原文

假设我有以下模型:

class Parent < ActiveRecord::Base
  has_one :child
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

我想通过子项检索父项,但执行以下操作失败: 我通过控制器按以下方式找到模型

@child = Child.find(params[:child_id])

(不确定这是否相关,但由于我使用的是浅层路由,因此 URL 中没有parent_id)

在我看来,我想检索孩子的父母像这样:

@child.parent

我该怎么做?

谢谢!


更新:我的示例(当我决定启动一个新应用程序并创建它时)实际上运行得很好。 在我的实际应用程序中,我忘记在子模型中包含 belongs_to :parent 。我真傻。感谢你们花时间发表评论和回答,伙计们。下次在此处发布问题之前我会更仔细地查看。

Say I have the following models:

class Parent < ActiveRecord::Base
  has_one :child
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

I'd like to retrive the parent through the child, but doing the following fails:
I find the model in the following way through a controller

@child = Child.find(params[:child_id])

(Not sure if this is relevant, but since I'm using shallow routing, the parent_id is not available in the URL)

In my view, I'd like to retrieve the child's parent like this:

@child.parent

How would I go about doing this?

Thanks!


Update: my example (when I decided to start a new app and create it) actually ran perfectly.
In my actual app, I forgot to include belongs_to :parent in the child's model. How silly of me. Thanks for taking the time to comment and answer, guys. Next time I'll look more carefully before posting a question here.

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

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

发布评论

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

评论(1

爱要勇敢去追 2024-10-16 01:07:45

你就是这么做的。

它不起作用的事实表明存在一些根本问题阻止 @child 拥有父级。

首先,检查 Child 表是否有外键。外键列(在本例中为 parent_id)应始终位于具有 belongs_to 关联的模型上。

其次,检查您要获取的孩子是否确实有父母。这意味着外键 (parent_id) 不应为零。如果它具有数值,请检查 Parent 表中是否有与 Child 中的foreign_key 具有相同值的记录。

您还可以使用 Rails 控制台(应用程序目录中的 rails console)来仔细检查关联。执行 Child.first.parent 看看发生了什么。当然,您也可以开始使用 Parent.first.childChild.find(123).parent 等变体,但不能使用 参数

That's exactly how you do it.

The fact that it's not working suggests there's some underlying issue preventing @child from having a parent.

First off, check that the table for Child has a foreign key. The foreign key column (in this case parent_id) should always be on the model that has the belongs_to association.

Secondly, check that the child you're fetching actually has a parent. This means that the foreign key (parent_id) should not be nil. If it has a numeric value, check that the table for Parent has a record with the same value as the foreign_key in Child.

You can also use the Rails console (rails console from your application directory) to double-check associations. Do Child.first.parent and see what's going on. Of course, you can start using variations such as Parent.first.child or Child.find(123).parent as well, but you can't use params.

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