Link_to() Rails 7

Hi, I just landed on Rails 7, and it’s great with the command to install CSS framework like tailwind on the fly. But when I use link_to with methods like :delete, and Rails always response with GET. I was read at the API documentation

Supported verbs are :post , :delete , :patch , and :put . Note that if the user has JavaScript disabled, the request will fall back to using GET

I tried at all my browser and it same, and never disable javascript at my browser. So how to fix this? I saw many solutions at StackOverflow but for prior Rails 7 with adding ujs, and we know ujs is not shipped again with Rails 7. I think this is a silly question about the HTTP verb not working in my case, so how to solve this?

2 Likes

I know the frontend is changing for Rails 7 so my info may be out-of-date. But historically those sorts of behaviors were implemented by Rails-UJS. That is included with Rails but you need to make sure it’s included with your JS.

I follow from DHH video from youtube (Alpha preview: Rails 7 w/ esbuild + Tailwind CSS - YouTube) using command rails new project --dev -j esbuild --css tailwind and i was tried using rails new project. the result is same HTTP verb read as GET when use method :delete.

What JS library must include at Rails to make this proper run?

Try data-turbo-method instead of data-method. Something like this should work:

<%= link_to "Log out", logout_path, data: {"turbo-method": :delete} %>

Make sure that turbo-rails gem and @hotwired/turbo-rails npm package are up-to-date.

3 Likes

I ran into the same issue some time ago and I found this issue on github: https://github.com/hotwired/turbo-rails/issues/33 and dug a little bit deeper and long story short:

you shouldn’t be using link_to for non idempotent actions such as POST, PUT, PATCH, DELETE you should be using button_to instead, which builds a form with method=“delete”. Something along these lines:

<%= button_to "Log out", logout_path, method: :delete %>
2 Likes

The library is Rails-UJS. Again I’m not sure if this is the way going forward in Rails 7 but that is how those data attributes have been implemented in the past.

1 Like

That may be the wrong link. I think it’s actually https://www.npmjs.com/package/@rails/ujs

1 Like

I stumbled upon the same problem and also went with the button_to solution as this generates a form including a csrf token :slight_smile:

Still is an issue. Using button_to fixed it for me, whereas using{"turbo-method": :delete} partially fixed it; it deleted the record but still tried to route it like it was a show method, which throws an error since there is no record with that id anymore.