3

I want to delete the nested object book, that is owned by a user. In the user#show page appears all the books related to that user. Besides each book there is a link to delete it. Here is my code:

routes.rb:

 resources :users do
   resources :books, :only => [:new, :create, :destroy]
 end

book_controller.rb:

def destroy
  @user= User.find(params[:user])
  @book = Book.find(params[:book])
  @book.destroy
  redirect_to current_user
end

And in the user#show page:

<%= link_to "Delete", user_book_path(current_user, book), :method => :delete %>

I know this is wrong, but how can I do it in order to deleted the wanted book?

ekremkaraca
  • 1,453
  • 2
  • 18
  • 37
Samth
  • 113
  • 1
  • 1
  • 5

1 Answers1

3

When you are deleting you can forget about the fact that it's a nested resource. You know which book you are talking about, so you can just delete it directly.

Routes:

resources :users do
  resources :books, :only => [:new, :create]
end

resources :books, :only => :destroy

Book controller:

def destroy
  @book = Book.find(params[:id])
  @book.destroy
  redirect_to current_user
end

View:

<%= link_to "Delete", book_path(book), :method => :delete %>
Mischa
  • 42,876
  • 8
  • 99
  • 111