无法删除我的工作人员模型的活动记录。
Workers与用户具有belongs_to关系
我的路线
workers_update PUT /workers/update(.:format) workers#update
user_workers POST /users/:user_id/workers(.:format) workers#create
new_user_worker GET /users/:user_id/workers/new(.:format) workers#new
edit_user_worker GET /users/:user_id/workers/:id/edit(.:format) workers#edit
user_worker GET /users/:user_id/workers/:id(.:format) workers#show
DELETE /users/:user_id/workers/:id(.:format) workers#destroy
我的工作人员控制器销毁方法
def destroy
@worker.destroy
redirect_to(current_user)
end
我正在尝试创建的按钮位于工作人员显示页面
<% if current_user?(@worker.user) %>
<%= button_to "Delete", @worker, method: :delete, data: {confirm: "Are you sure you want to delete this worker?"}%>
<%end%>
我尝试加载页面时收到的错误
NoMethodError in Workers#show
Showing /home/elliot/rails_projects/EJWmining_app/mining_app/app/views/workers/show.html.erb where line #10 raised:
undefined method `worker_path' for #<#<Class:0x00000002b841e0>:0x00000003e5e338>
Extracted source (around line #10):
9: <% if current_user?(@worker.user) %>
10: <%= button_to "Delete", @worker, method: :delete, data: {confirm: "Are you sure you want to delete this worker?"}%>
11: <%end%>
不确定我为什么会收到此错误。它表示在Workers#中没有方法错误,表明它应该调用Workers#destroy。奖励积分我们可以将我的引导按钮类添加到此按钮
class: "btn btn-small bit-danger"
答案 0 :(得分:6)
发生这种情况的原因是当你使用像@worker
这样的实例变量url_to
(link_to
或button_to
之内)时会处理它将假设基于类名的路由。
在这种情况下,您的课程为Worker
。由于@worker
是Worker
,因此它尝试使用worker_path
,但您实际上并未定义该路由。对于一个简单的资源,路由看起来像这样:
new_worker GET /workers/new(.:format) workers#new
edit_worker GET /workers/:id/edit(.:format) workers#edit
worker GET /workers/:id(.:format) workers#show
PUT /workers/:id(.:format) workers#update
DELETE /workers/:id(.:format) workers#destroy
DELETE
worker_path
就是你想要的。但是,由于您有一些更复杂的路线,您实际上需要user_worker_path
。
你可以使用它:
<%= button_to "Delete", user_worker_path(@user, @worker), method: :delete, ... %>
更多信息:
要添加课程,您可以直接将其添加到button_to
代码中:
<%= button_to "Delete", path_method, method: 'delete', class: 'myclass' %>
希望这有帮助!