[Form object] How to make one form usable by both POST and PATCH (PUT)

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:

Recommended for people like this

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

Only two things to do

(1) Added method :: 〇〇 to the side that calls the form (render). (○○ is post, patch, etc.) (2) Add method: method on the form side.

(1) Form caller

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).

(2) Form side

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.

background

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.

Click here for reference articles

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

environment

ruby: 2.7.1 rails: 6.0.3.3

Recommended Posts

[Form object] How to make one form usable by both POST and PATCH (PUT)
Memorandum to make CentOS 7.9 and put pacemaker
How to check only one RadioButton check by default (Note)
I tried to make an app that allows you to post and chat by genre ~ App overview ~
What is an immutable object? [Explanation of how to make]