如何删除与父控制器更新操作的关联? Rails
How to delete association with parent controller update action? Rails
我正在使用 Rails 4
我需要使用 link_to
方法删除关联 Box
。问题是我必须从父控制器和 method: patch
进行操作。我的 corrent 代码什么都不做,因为我不知道如何将 data:
用于 link_to.
#views/modifications/show.html.erb
<% @modification.boxes.each do |box| %>
<tr>
<td><%= box.name %></td>
<td><%= link_to "delete", @modification, remote: true, method: :patch %></td>
</tr>
<% end %>
顺便说一句,这与 Ajax 一起使用,因此不需要重新加载页面。
尝试在盒子销毁路径上使用 link_to
和 delete 方法,如下所示:
<%= link_to 'Delete', box_path(box), method: :delete, remote: true %>
I have to do it
您没有以任何方式做任何事情 - 如果微软可以为所有 PC 发布 Windows在这个世界上,我相信你能做到这一点。
您有几个问题,其中最重要的是... 您如何识别要删除的 box
对象?
nested resources
的全部要点(这正是您所需要的)是让您能够识别 "parent" 对象 和 子对象.
您当前的设置使您无法识别要删除的 box
。理想情况下,您应该使用以下代码对其进行排序:
#config/routes.rb
resources :modifications do
resources :boxes, only: :destroy
end
#app/views/modifications/show.html.erb
<% @modification.boxes.each do |box| %>
<tr>
<td><%= box.name %></td>
<td><%= link_to "delete", [@modification, box], remote: true, method: :delete %></td>
</tr>
<% end %>
#app/controllers/boxes_controller.rb
class BoxesController < ApplicationController
def destroy
@modification = Modification.find params[:modification_id]
@box = @modification.boxes.find params[:id]
@box.destroy
end
end
我正在使用 Rails 4
我需要使用 link_to
方法删除关联 Box
。问题是我必须从父控制器和 method: patch
进行操作。我的 corrent 代码什么都不做,因为我不知道如何将 data:
用于 link_to.
#views/modifications/show.html.erb
<% @modification.boxes.each do |box| %>
<tr>
<td><%= box.name %></td>
<td><%= link_to "delete", @modification, remote: true, method: :patch %></td>
</tr>
<% end %>
顺便说一句,这与 Ajax 一起使用,因此不需要重新加载页面。
尝试在盒子销毁路径上使用 link_to
和 delete 方法,如下所示:
<%= link_to 'Delete', box_path(box), method: :delete, remote: true %>
I have to do it
您没有以任何方式做任何事情 - 如果微软可以为所有 PC 发布 Windows在这个世界上,我相信你能做到这一点。
您有几个问题,其中最重要的是... 您如何识别要删除的 box
对象?
nested resources
的全部要点(这正是您所需要的)是让您能够识别 "parent" 对象 和 子对象.
您当前的设置使您无法识别要删除的 box
。理想情况下,您应该使用以下代码对其进行排序:
#config/routes.rb
resources :modifications do
resources :boxes, only: :destroy
end
#app/views/modifications/show.html.erb
<% @modification.boxes.each do |box| %>
<tr>
<td><%= box.name %></td>
<td><%= link_to "delete", [@modification, box], remote: true, method: :delete %></td>
</tr>
<% end %>
#app/controllers/boxes_controller.rb
class BoxesController < ApplicationController
def destroy
@modification = Modification.find params[:modification_id]
@box = @modification.boxes.find params[:id]
@box.destroy
end
end