Search code examples
ruby-on-railsrubydebuggingroutesruby-on-rails-7

Rails 7 won't generate a destroy path for the comment deletion


I'm trying to make a delete helper for a comment, this is the html code :

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

And this is the routes I have :

'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

But when I run rails routes in console, I only get those helpers for the comments controller:

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

As you can see, the destroy route has no helper, I need it so I can call it to match the action in the comment controller


Solution

  • You're getting confused between paths and route helpers. As you can see, the URL for the delete operation is the same as for update. You can just use that helper in order to create the path/URL and just use the *method: :delete option as you already are.

    That being said, in Rails 7 (sans rails-ujs) you won't be able to use link_to, you'll need to use button_to so it creates a little form.