![](/img/trans.png)
[英]Rails 4, Unknown action, The action 'destroy' could not be found for PostsController
[英]Rails The action 'destroy' could not be found error
我已经看到有关此问题的类似问题,但是那里提供的解决方案似乎对我来说不是问题。
我有一个页面,用户可以选择编辑或删除位置文件,并且每个块都对此进行编码:
<%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找不到我的销毁动作(重定向对其他动作也能正常工作)。
您正在链接中调用method: :delete
,这是正确的。
我看到的唯一另一个问题是您拼写了destroy
错误。 你拼写它destory
像“DEE-STOR-EE”。
我也会删除这条路线:
get 'locations/:id/destory' => 'locations#destory' #=> wouldn't work anyways because it's not a "delete" request
因为您已经在调用resources :locations
。
做这个:
#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?" } %>
根据文档 :
link_to(name = nil(link text), options = nil (controller/url), html_options = nil(class/id/data), &block)
这些问题让我惊讶:
首先,解决destory
错别字。
# routes
'locations/:id/destroy' => 'locations#destroy'
#controller
def destroy
其次,使用HTTP DELETE动词进行destroy
。
delete 'locations/:id/destroy' => 'locations#destroy'
最后,link_to应该指定位置路径。
<%= link_to "delete", location_path(l), class: "bg-danger", method: :delete,
data: { confirm: "You sure?" } %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.