How do I find a child's parent through a has_one association in Rails3?
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 th开发者_如何学Pythone 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.
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
.
精彩评论