Rails - 嵌套对象删除

发布于 2024-11-11 17:09:08 字数 685 浏览 5 评论 0原文

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

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

我知道这是错误的,但是如何我可以删除想要的书吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千仐 2024-11-18 17:09:08

当您删除时,您可能会忘记它是嵌套资源这一事实。你知道你说的是哪本书,所以直接删除就可以了。

路线:

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

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 %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文