开发者

Linking a new child with its parent when adding a new child

开发者 https://www.devze.com 2023-01-09 17:07 出处:网络
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. Ri

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 th开发者_开发知识库is customer" rails knows that I'm adding a new event for that particular customer instead of having to put in the customer_id myself?


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) %>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消