添加新子项时将新子项与其父项链接
我有一个 customer
模型,它有很多 events
当我转到客户展示页面时,我有指向以下人员拥有的所有 events
的链接客户
。我想添加“此客户的新活动”链接。现在,我正在使用 <%= link_to "New Event for this Customer", new_event_path %>
执行此操作,但是当我点击该链接时,我必须手动输入客户的 ID 号。如何自动执行此操作,以便当我单击“为此客户添加新事件”时,rails 知道我正在为该特定客户添加新事件,而不必自己输入 customer_id?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找的内容称为
嵌套资源
,这是一个很好的介绍。对于这种特定情况,您应该像这样声明您的路由:
上述声明将允许您定义如下路由:
在您的特定情况下:
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:
The above declaration would allow you to define routes like:
And in your specific case:
将客户 ID 作为参数添加到链接
<%= link_to "New Event for this Customer", new_event_path, {:cust_id => customer.id} %>
并在表单中将其设置为事件对象的隐藏参数。您的模型将自动填充客户 ID。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.