Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top