views:

18

answers:

2

I have a customer model that has_many events When I go to the customer show page, I have links to all of the events that are owned by customer. I want to add a "New event for this customer" link. Right now, I'm doing that with <%= link_to "New Event for this Customer", new_event_path %> but when I follow that link, I have to manually enter in the customer's id number. How can I automate this so that when I click "Add new event for this customer" rails knows that I'm adding a new event for that particular customer instead of having to put in the customer_id myself?

A: 

Add the customer id to the link as parameter <%= link_to "New Event for this Customer", new_event_path, {:cust_id => customer.id} %> and in the form, set this as a hidden param for event object. Your model will automatically be populated with the customer id.

Teja Kantamneni
+2  A: 

What you are looking for is called nested resources, here's a good introduction.

For this specific case you should declare your routes like these:

map.resources :customers do |customers|
   customers.resources :events
end

The above declaration would allow you to define routes like:

new_customer_event_url(@customer.id)
=> customers/:customer_id/events/new

And in your specific case:

<%= link_to "New Event for this Customer", new_customer_event_path(@customer) %>
jpemberthy
This worked perfectly, thank you. My next question is once I'm at the child, how do I link back to its parent show page?
Reti
You'll be able to define the following link, `link_to "Customer", customer_path(@customer)` assuming you are defining `@customer` in your controller. Maybe `def find_customer; @customer = Customer.find(params[:customer_id]); end;`
jpemberthy
PD, If you wish to view all the generated routes for `customers` you can always run `rake routes | grep customer` that helps a lot.
jpemberthy