Rails 7无法生成评论删除的destroy路径助手问题
解决评论删除功能的路由助手问题
问题根源
你手动添加的DELETE路由属于冗余配置,且错误调用了不存在的路由助手方法。Rails的RESTful嵌套路由已经自动为destroy动作生成了对应路由和助手,无需额外手动定义。
步骤1:清理路由配置
删除你手动添加的这条路由:
'delete /store_posts/:store_post_id/store_comments/:id', to : 'store_comment#destroy'
保留嵌套资源的核心配置即可:
resources :store_posts do resources :store_comments, only: [:create, :edit, :update, :new, :destroy] end
步骤2:修正视图中的路由助手
RESTful路由规则下,嵌套资源的destroy动作对应的助手方法是单数形式的store_post_store_comment_path,你已经通过turbo-method: :delete配置了正确的请求方法,只需替换路径助手并传递正确参数:
<% if store_comment.user_id == current_user.id %> <%= link_to 'edit', edit_store_post_store_comment_path(store_post, store_comment) %> <%= link_to 'delete', store_post_store_comment_path(store_post, store_comment), data: { 'turbo-method': :delete, turbo_confirm: 'You sure?'} %> <% end %>
补充说明
- 你在
rails routes输出中看到的DELETE路由,和PATCH/PUT共享同一路径/store_posts/:store_post_id/store_comments/:id,对应的助手方法就是第一行标注的store_post_store_comment_path,Rails通过请求方法(DELETE/PATCH/PUT)区分执行destroy/update动作。 - 如果你是用
name作为store_post的URL标识(而非默认的id),需要在store_posts路由中添加param: :name,确保参数传递有效:resources :store_posts, param: :name do resources :store_comments, only: [:create, :edit, :update, :new, :destroy] end
内容的提问来源于stack exchange,提问作者John Sall
相关产品推荐
相关产品推荐

