Operating environment Ruby 2.6.5 Rails 6.0.3.2
When I used form_with, I often made an error without noticing that the name attribute and id attribute were automatically assigned, so I posted it.
ruby:new.html.erb
<%= form_with model: @hoge, local: true do |f| %>
<%= f.text_field :fuga %>
<%= f.submit "Post" %>
<% end %>
As mentioned above, if you specify model as @hoge and check the name attribute and id attribute with the verification tool, it will be ** name = "hoge [fuga]", id = "hoge_fuga" **. Even though name and id are not specified, name attribute and id attribute are automatically assigned.
In the previous code, it was said that if you do not specify the name attribute and id attribute, it will be assigned automatically, but let's see what happens if you specify the name attribute and id attribute.
ruby:new.html.erb
<%= form_with model: @hoge, local: true do |f| %>
<%= f.text_field :fuga, name:"hogera", id:"piyo" %>
<%= f.submit "Post" %>
<% end %>
As before, if you check the name attribute and id attribute with the verification tool, it will be ** name = "hogera", id = "piyo" **. That is, the name and id attributes are as specified.
Next, let's see what happens if you specify a url instead of specifying a model.
ruby:new.html.erb
<%= form_with url: hoges_path, local: true do |f| %>
<%= f.text_field :fuga %>
<%= f.submit "Post" %>
<% end %>
As before, if you check the name attribute and id attribute with the verification tool, it will be ** name = "fuga", id = "fuga" **. One thing to note here is that the name and id attributes are different from when model is specified. Basically, if the action you want to perform on the controller is the same, the result will not change whether you specify model or url, but the name attribute and id attribute are different.
By the way, if you specify both model and url, the name and id attributes will be the same as if you specify model.
I was surprised when I learned this because I thought that the name and id attributes would not be granted unless I specified them. Also, I used to get the name attribute using JavaScript, but at that time, I struggled with the error for hours without noticing the difference between the name attribute when model was specified and when the url was specified. There was a case that it ended up.
In order to prevent such an error, why not specify both the name attribute and id attribute from the beginning? I thought, but in the first place, it is automatically given to reduce the amount of description, so it seems that I often use the one given automatically without specifying it myself.