Having trouble deleting an active record for my model of workers.
Workers has a belongs_to relationship with Users
My routes
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
My worker controller destroy method
def destroy
@worker.destroy
redirect_to(current_user)
end
The button I'm trying to create which is on the worker show page
<% if current_user?(@worker.user) %>
<%= button_to "Delete", @worker, method: :delete, data: {confirm: "Are you sure you want to delete this worker?"}%>
<%end%>
The error I get when I try and load the page
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%>
Not sure why I am getting this error. it says no method error in Workers#show it should be calling Workers#destroy. Bonus points we can add my bootstrap button class to this button
class: "btn btn-small bit-danger"
The reason this is happening is that when you use an instance variable like @worker somewhere that url_to (inside of link_to or button_to, among others) will process it will assume routes based on the classname.
In this case your class is Worker. Since @worker is a Worker it is trying to use worker_path, but you don't actually have that route defined. For a simple resource, routes would look like this:
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
So a DELETE on worker_path would be what you want. However since you have some more complicated routes going you actually want user_worker_path.
You could use this like:
<%= button_to "Delete", user_worker_path(@user, @worker), method: :delete, ... %>
More information:
To add the class you can include it in the button_to code directly:
<%= button_to "Delete", path_method, method: 'delete', class: 'myclass' %>
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With