I am trying to create a simple app in Rails, where a user can list to-do items and delete them once completed. I'm having trouble with being able to destroy items. Each time I try this, the browser gives the following error:
ActiveRecord::RecordNotFound in UsersController#destroy Couldn't find Item with 'id'=11
I've tried various edits to the controller and _item partial.
Here are a couple links of some previous stack overflow questions/answers that I've tried to implement in order to fix this:
ActiveRecord::RecordNotFound - Couldn't find User without an ID
Couldn't find <Object> without an ID (Deleting a record)
I am using devise, Rails 5.0.0.1, and Ruby 2.3.1 (if that helps).
Here's my code:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def destroy
Item.find(params[:id]).destroy
end
end
class ItemsController < ApplicationController
def create
@item = current_user.items.new(items_param)
if @item.save
flash[:notice] = "Item was saved successfully."
redirect_to current_user
else
flash.now[:alert] = "Error creating item. Please try again."
render :new
end
end
def destroy
@item = Item.find(params[:id])
@item.destroy
end
private
def items_param
params.require(:item).permit(:name)
end
end
Here is the item partial _item.html.erb:
<%= content_tag :div, class: 'media', id: "item-#{item.id}" do %>
<%= link_to "", @item, method: :delete, class: 'glyphicon glyphicon-ok' %>
<%= item.name %>
<% end %>
Routes.rb:
Rails.application.routes.draw do
devise_for :users
resources :users, only: [:show, :destroy] do
resources :items, only: [:create, :show, :destroy]
end
root 'users#show'
end
Browser Error:
ActiveRecord::RecordNotFound in UsersController#destroy Couldn't find Item with 'id'=11
What am I doing wrong?