For a long time, Rails has provided a method: :post
option in the link_to
helper: when the option was given, Rails would intercept the click and issue a POST request, instead of the default GET request.
However, for some unknown reason, this is not working in Rails 7: despite adding method: :post
to my link_to
helper, Rails sends a GET request (not a POST request). I thought Turbo was supposed to take care of it, but it does not seem to be happening.
This is what you can do to reproduce, very simple steps:
$ rails new example_app
$ bin/rails g scaffold Book title
$ bin/rails db:create && bin/rails db:migrate
$ echo "<%= link_to "New book", new_book_path, method: :post %>" >> app/views/books/index.html.erb
$ bin/rails s
Now visit localhost:3000/books
from your web browser, and click on the second "New book" link. I would expect getting an error (after all, I did not configure the proper POST route) but, unfortunately, Rails isues a GET request - and not a POST request, as it should have:
Started GET "/books/new" for ::1 at 2021-12-27 17:40:43 +0100
Processing by BooksController#new as HTML
Rendering layout layouts/application.html.erb
Rendering books/new.html.erb within layouts/application
Rendered books/_form.html.erb (Duration: 9.1ms | Allocations: 5216)
Rendered books/new.html.erb within layouts/application (Duration: 10.2ms | Allocations: 5594)
Rendered layout layouts/application.html.erb (Duration: 12.9ms | Allocations: 7759)
Completed 200 OK in 25ms (Views: 13.6ms | ActiveRecord: 4.3ms | Allocations: 12404)
Why is this happening? Shouldn't Turbo intercept the link, and, as Rails UJS did in the past, send a POST request?