Rails - 嵌套对象删除

时间:2011-05-30 14:54:19

标签: ruby-on-rails ruby-on-rails-3 actioncontroller nested-resources

我想删除由book拥有的嵌套对象user。在user#show页面中,显示与books相关的所有user。除了每本书外,还有一个指向delete的链接。这是我的代码:

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

user#show页面中:

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

我知道这是错的,但我怎么能这样才能删除想要的书呢?

1 个答案:

答案 0 :(得分:3)

当你删除时,你可以忘记它是一个嵌套资源的事实。你知道你在说哪本书,所以你可以直接删除它。

路线:

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

resources :books, :only => :destroy

图书管理员:

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

查看:

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