# How to reference parent object when using sub-resources

**URL:** <https://www.ruby-forum.com/t/how-to-reference-parent-object-when-using-sub-resources/157023>\
**Category:** Rails\
**Created:** [January 6, 2009, 3:20pm UTC](https://www.ruby-forum.com/t/how-to-reference-parent-object-when-using-sub-resources/157023 "2009-01-06T15:20:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pooch](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/dbc845/32.png) [@pooch](https://www.ruby-forum.com/u/pooch)\
**Post date:** [January 6, 2009, 3:20pm UTC](https://www.ruby-forum.com/t/how-to-reference-parent-object-when-using-sub-resources/157023/1 "2009-01-06T15:20:03Z")

</div>

Hi,

I’m building my first Rails application and have hit a problem using  
sub-resources.

My model includes a Deposit that has\_many Payments. So routes.rb has  
a line:

```
   map.resources :deposits, :has_many => :payments

```

I’ve generated the scaffolding for Payments and I am able to go from a  
particular Deposit to a page where I want to show its list of  
Payments. The index.html.erb for Payments begins with these 2 lines:

```
 <h2>Payments for deposit <%= @deposit.deposit_date %> : <%=

```

@deposit.name %\>

```
 <%= link_to 'Add a payment', new_payment_path(@deposit) %>

```

The references to @deposit in the first line are resolved correctly,  
but not so on the second line. When trying to render the index, the  
error messages I get are:

```
 NoMethodError in Payments#index
 You have a nil object when you didn't expect it!
 The error occurred while evaluating nil.to_sym

```

This at first made me think that @deposit was nil when the second line  
was parsed, but now I think that the first error line is more to the  
point – there isn’t a new\_payment\_path method that takes a Deposit as  
a parameter. But I need to pass in the parent Deposit on the page  
where I will be creating a child Payment, so how can I do that?

When I remove the @deposit parameter from new\_payment\_path, the page  
renders fine, but when I click the Add a Payment link, the page it  
goes to is [http://localhost:3000/payments/new](http://localhost:3000/payments/new) , with no reference to  
the parent Deposit.

So how do I pass in the parent when creating the child?

Thanks!

---

<div class="post-metadata">

**Author:** ![pooch](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/dbc845/32.png) [@pooch](https://www.ruby-forum.com/u/pooch)\
**Post date:** [January 6, 2009, 3:41pm UTC](https://www.ruby-forum.com/t/how-to-reference-parent-object-when-using-sub-resources/157023/2 "2009-01-06T15:41:15Z")

</div>

Nevermind – I’ve found the answer. The link\_to should be coded as:

```
 <%= link_to 'Add a payment', new_deposit_payment_path(@deposit)

```

%\>

For me, magic is often hard to follow.
