Ruby on Rails: forget link_to with :method

← Back

Since Rails 7.0, Rails UJS library is deprecated. That means that

link_to 'Remove post', post_path(@post), :data => { :method => :delete, :confirm => 'Are you sure?' }

is no longer the way. Actually, ever since UJS has been around, it has never been “the way.” The documentation explains why:

Note that if the user has JavaScript disabled, the request will fall back to using GET.

The right way

  1. Decide whether you want the confirmation. For many cases (e.g., deleting), you will. In other cases (e.g., (de)activation), not.
  2. Add confirmation routes where you need them:
       resources :posts do
         member do
           get :confirm_delete
         end
       end
    

    (And also the related controller action and view.)

  3. Link to the confirmation page. There, present enough information about the object being deleted and use #button_to for simplicity:
       button_to 'Remove post', post_path(@post), :method => :delete
    
  4. For no-confirmation-requiring actions, simply use the mentioned #button_to helper. It generates a standard <form> for you.

Tagged with: Ruby on Rails, JavaScript

Written: 2022-09-15