添加新孩子时将新孩子与其父母链接
问题描述:
我有一个customer
模型has_many events
当我进入顾客显示页面时,我链接到customer
拥有的所有events
。我想添加一个“此客户的新活动”链接。现在,我正在使用<%= link_to "New Event for this Customer", new_event_path %>
,但是当我遵循该链接时,我必须手动输入客户的ID号。我如何自动执行此操作,以便当我单击“为此客户添加新事件”时,rails知道我为该特定客户添加了新事件,而不必自己输入customer_id?添加新孩子时将新孩子与其父母链接
答
你在找什么叫做nested resources
,这里是good introduction。
对于这个特定的情况下,你应该声明你的路由这样的:
map.resources :customers do |customers|
customers.resources :events
end
以上声明将允许你定义喜欢的路线:
new_customer_event_url(@customer.id)
=> customers/:customer_id/events/new
并在您的具体情况:
<%= link_to "New Event for this Customer", new_customer_event_path(@customer) %>
答
将客户ID添加到链接中作为参数<%= link_to "New Event for this Customer", new_event_path, {:cust_id => customer.id} %>
,并在窗体中将其设置为事件对象的隐藏参数。您的模型将自动填入客户ID。
这很好,谢谢。我的下一个问题是一旦我在孩子身边,我该如何链接回其父母展示页面? – Reti 2010-07-29 20:20:25
假设您在控制器中定义了“@ customer”,您将能够定义以下链接,link_to“Customer”,customer_path(@customer)'。也许'def find_customer; @customer = Customer.find(params [:customer_id]); end;' – jpemberthy 2010-07-29 21:07:45
PD,如果你想查看'customers'的所有生成路由,你总是可以运行'rake routes | grep客户',这有助于很多。 – jpemberthy 2010-07-29 21:11:24