3

无法删除我的工人模型的活动记录。

Workers 与 Users 有 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#show中没有方法错误,它应该调用Workers#destroy。奖励积分我们可以将我的引导按钮类添加到此按钮

class: "btn btn-small bit-danger"
4

1 回答 1

6

发生这种情况的原因是,当您使用某个实例变量@worker(例如url_tolink_toor内部button_to等)将进行处理时,它将假定基于类名的路由。

在这种情况下,您的课程是Worker. 由于@workeris aWorker它正在尝试使用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

所以 a DELETEonworker_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' %>

希望这可以帮助!

于 2013-07-06T00:26:51.360 回答