添加新子项时将新子项与其父项链接

发布于 2024-09-12 01:20:50 字数 337 浏览 7 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悟红尘 2024-09-19 01:20:50

您正在寻找的内容称为嵌套资源,这是一个很好的介绍

对于这种特定情况,您应该像这样声明您的路由:

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

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) %>
递刀给你 2024-09-19 01:20:50

将客户 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文