Rails - delete nested objects

I want to delete a nested object bookthat belongs user. The page user#showdisplays everything booksrelated to this user. In addition to each book there is a link to deleteit. 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 on the page user#show:

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

I know this is wrong, but how can I do this to delete the book I need?

+3
source share
1 answer

When you delete, you may forget that it is an embedded resource. You know which book you are talking about, so you can simply 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 %>
+3
source

All Articles