Reputation: 886
Any help or guidance would be very much appreciated.
Deleting a List works, however, when I clicked on the shopping lists after deleting a list breaks the show action for the rest of the lists below them? These were working before I added a delete action.
Coming from this URL http://localhost:3000/lists
ActiveRecord::RecordNotFound in ListsController#show
Couldn't find Product with 'id'=7
List_controller (condensed)
def show
@list = List.find(params[:id])
@product = Product.find(params[:id])
end
def destroy
@list = List.find(params[:id])
@list.destroy
redirect_to lists_path, notice: 'List was deleted.'
end
Show Lists
<%= link_to 'Delete', list_path(list), method: :delete, data: { confirm: 'Are you sure?'} %>
List.rb
class List < ApplicationRecord
belongs_to :user
has_many :products, dependent: :destroy
has_many :comments, dependent: :destroy
accepts_nested_attributes_for :products
end
Should also delete Child/Associated Products included in the list.
class Product < ApplicationRecord
belongs_to :list, optional: true
has_one_attached :hero
end
show.html.erb
<%= content_tag(:h1, "Listing All Shopping Lists") %>
<table>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
<% @list.each do |list| %>
<tr>
<td><%= list.name %></td>
<td><%= link_to 'Show', list_path(list) %></td>
<td><%= link_to 'Delete', list_path(list), method: :delete, data: { confirm: 'Are you sure?'} %></td>
</tr>
<% end %>
</table>
Upvotes: 0
Views: 47
Reputation: 886
Thank you to everyone for your intervention - I am enamoured by the SO community!
The issue was in my list controller#show from
def show
@list = List.find(params[:id])
@product = Product.find(params[:id])
end
to
def show
@list = List.find(params[:id])
end
I think this is something to do with the hidden id attribute which follows you around. The product :id was in conflict with the list :id in this action.
I am not sure why this error manifests itself when you delete an item.
However, removing it works.
Upvotes: 1
Reputation: 1208
You have has_many :products, dependent: :destroy
in your List model. That causes the deletion of all products belonging to this list. You should add dependent: :nullify if you want to keep the products.
I assume you are in the show action of a non existing product.
Upvotes: 1