How to reference parent object when using sub-resources


#1

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 , with no reference to
the parent Deposit.

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

Thanks!


#2

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.