This is a method to use one form properly with multiple HTTP methods. Note that it was difficult to implement with a form object.
Feel free to let me know if there is another better way: innocent:
-Those who implement the form with a form object. -People who want to use the same form for new creation and editing when submitting information with a form.
(1) Added method :: 〇〇 to the side that calls the form (render). (○○ is post, patch, etc.) (2) Add method: method on the form side.
ruby:example.html.erb
<%= render "Form template path", url:Path of the action you want to call, method: :〇〇 %>
For new creation, set 〇〇 to post, and for editing, set patch (put).
ruby:_example_form.html.erb
<%= form_with model:Model instance, url: url, method: method do |f| %>
Normally, I think that url and method are specified directly here, but I dare to make it a variable. By doing so, it can be used for both new creation and editing.
I should have defined the PATCH path (url) in render, but it was actually sent by POST. It seems that the cause is PATCH if the instance described in model: of the form exists, and POST if it does not exist, as described in the following article. If you use a form object, an instance will be created each time you submit a form, so it will always be POST and will not work as expected. Therefore, we also define a method to avoid this problem.
https://qiita.com/snskOgata/items/44d32a06045e6a52d11c#2-form_with%E3%81%AE%E5%8B%95%E4%BD%9C%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6
ruby: 2.7.1 rails: 6.0.3.3
Recommended Posts