我已经看到有关此问题的类似问题,但那里提供的解决方案对我来说似乎不是问题。
我有一个页面,用户可以选择编辑或删除位置文件,并使用每个块进行编码:
<%current_user.locations.reverse.each do |l|%>
<%=l.address %>
<a href=<%= edit_location_path(l) %> class="btn btn-primary">Edit</a>
| <%= link_to "delete" class="bg-danger", l, method: :delete,
data: { confirm: "You sure?" } %>
<br>
<%end%>
我有我的路线(必须尝试修复此错误):
get 'locations/:id/delete' => 'locations#destroy'
get 'locations/:id/destory' => 'locations#destory'
resources :locations
我在locaction控制器中编码:
def destory
@location = Location.find(params[:id])
@deleted_address = @location.address
@location.destroy
flash[:danger] = @deleted_address + " deleted"
redirect_to current_user
end
我无法弄清楚为什么rails无法找到我的销毁操作(重定向适用于其他操作)。
答案 0 :(得分:1)
您在链接中呼叫method: :delete
,这是正确的。
我看到的唯一其他问题是你拼错了destroy
错误。你拼写它destory
喜欢&#34; dee-stor-ee&#34;。
我也会删除这条路线:
get 'locations/:id/destory' => 'locations#destory' #=> wouldn't work anyways because it's not a "delete" request
因为您已经在调用resources :locations
。
答案 1 :(得分:1)
这样做:
#config/routes.rb
resources :locations #-> DELETE url.com/locations/:id goes to destroy action
#view
<%current_user.locations.reverse.each do |l|%>
<%=l.address %>
<%= link_to "Edit", l, class: "btn btn-primary" %>
<%= link_to "Delete", l, method: :delete, class: "bg-danger", data: { confirm: "You sure?" } %>
<% end %>
这会向您的locations#destroy
行动发送请求。
您目前遇到的问题是您以某种奇怪的顺序呼叫link_to
:
<%= link_to "delete" class="bg-danger", l, method: :delete, data: { confirm: "You sure?" } %>
......应该......
<%= link_to "Delete", l, method: :delete, class: "bg-danger", data: { confirm: "You sure?" } %>
根据docs:
link_to(name = nil(link text), options = nil (controller/url), html_options = nil(class/id/data), &block)
答案 2 :(得分:0)
这些问题突然发生在我身上:
首先,修复destory
拼写错误。
# routes
'locations/:id/destroy' => 'locations#destroy'
#controller
def destroy
其次,对destroy
使用HTTP DELETE谓词。
delete 'locations/:id/destroy' => 'locations#destroy'
最后,link_to应指定位置路径。
<%= link_to "delete", location_path(l), class: "bg-danger", method: :delete,
data: { confirm: "You sure?" } %>