如何通过 Rails3 中的 has_one 关联找到孩子的父母?
假设我有以下模型:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你就是这么做的。
它不起作用的事实表明存在一些根本问题阻止
@child
拥有父级。首先,检查
Child
表是否有外键。外键列(在本例中为parent_id
)应始终位于具有belongs_to
关联的模型上。其次,检查您要获取的孩子是否确实有父母。这意味着外键 (
parent_id
) 不应为零。如果它具有数值,请检查Parent
表中是否有与Child
中的foreign_key 具有相同值的记录。您还可以使用 Rails 控制台(应用程序目录中的
rails console
)来仔细检查关联。执行Child.first.parent
看看发生了什么。当然,您也可以开始使用Parent.first.child
或Child.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 caseparent_id
) should always be on the model that has thebelongs_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 forParent
has a record with the same value as the foreign_key inChild
.You can also use the Rails console (
rails console
from your application directory) to double-check associations. DoChild.first.parent
and see what's going on. Of course, you can start using variations such asParent.first.child
orChild.find(123).parent
as well, but you can't useparams
.