gpt4 book ai didi

ruby-on-rails - Rails - 嵌套对象删除

转载 作者:行者123 更新时间:2023-12-02 00:32:27 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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

路线:

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

resources :books, :only => :destroy

书籍 Controller :

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

查看:

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

关于ruby-on-rails - Rails - 嵌套对象删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6177805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com