开发者

Rails - Nested Objects Deletion

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开发者_JS百科:

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?


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 %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜