Techioz Blog

Rails 7 はコメント削除の破棄パスを生成しません [クローズド]

概要

コメントの削除ヘルパーを作成しようとしています。これはHTMLコードです:

<% if store_comment.user_id == current_user.id %>
    <%= link_to 'edit', edit_store_post_store_comment_path(params[:name], store_comment.id) %>
    <%= link_to 'delete', delete_store_post_store_comment_path(params[:name], store_comment.id), data: { 'turbo-method': :delete,
                        turbo_confirm: 'You sure?'} %>

<% end %>

そして、これが私が持っているルートです:

'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

ただし、コンソールで Rails ルートを実行すると、コメント コントローラーのヘルパーのみが取得されます。

store_post_store_comments      POST   /store_posts/:store_post_id/store_comments(.:format)                                              store_comments#create
new_store_post_store_comment   GET    /store_posts/:store_post_id/store_comments/new(.:format)                                          store_comments#new
edit_store_post_store_comment  GET    /store_posts/:store_post_id/store_comments/:id/edit(.:format)                                     store_comments#edit
store_post_store_comment       PATCH  /store_posts/:store_post_id/store_comments/:id(.:format)                                          store_comments#update
                               PUT    /store_posts/:store_post_id/store_comments/:id(.:format)                                          store_comments#update
                               DELETE /store_posts/:store_post_id/store_comments/:id(.:format)                                          store_comments#destroy

ご覧のとおり、destroy ルートにはヘルパーがありません。コメント コントローラーのアクションと一致するように呼び出すことができるようにするために必要です。

解決策

パスとルート ヘルパーの間で混乱しています。ご覧のとおり、削除操作の URL は更新の URL と同じです。そのヘルパーを使用してパス/URL を作成し、すでに使用しているように *method: :delete オプションを使用するだけです。

そうは言っても、Rails 7 (rails-ujs なし) では link_to を使用できません。小さなフォームを作成するために button_to を使用する必要があります。