I have a one to many relationship with menus and items. I have got a nested resource setup with the add and create actions for adding items to that specific menu. With a list of all items in that menu. All of that works fine, but I am having problems with the destroy action.
I get the error:
The action 'destroy' could not be found for ItemsController
As you can tell from the code below the destroy action is in ItemsController and is not under private so I do not know why it cannot be found.
class ItemsController < ApplicationController
before_action :find_menu
def create
@item = @menu.items.create!(item_params)
if @item.save
redirect_to @menu, notice: "Item added!"
else
redirect_to @menu, warning: "Item failed!"
end
end
def destroy
@item = @menu.items.find(params[:id])
@item.destroy
redirect_to @menu, notice: "Item deleted!"
end
private
def find_menu
@menu = Menu.find(params[:menu_id])
end
def item_params
params.require(:item).permit(:name, :price, :course, :vegetarian, :allergy, :menu_id)
end
end
<tbody>
<% @items.each do |item| %>
<tr>
<td><%= item.name %></td>
<td><%= number_to_currency(item.price, unit: "£") %></td>
<td><%= item.course %></td>
<td><%= item.vegetarian %></td>
<td><%= item.allergy %></td>
<td><%= link_to "Delete", [@menu, item], method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-danger" %></td>
</tr>
<% end %>
</tbody>
def show
@menu = Menu.find(params[:id])
@items = @menu.items
end
This line:
<td><%= link_to "Delete", [@menu, item], method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-danger" %></td>
should look like:
<td><%= link_to "Delete", menu_item_path(@menu, item), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-danger" %></td>