When I was playing with the code to improve the portfolio, I found the description using form_for. Rewritten to form_with, an easy idea. .. ..
ruby 2.5.1p57 rails (6.0.3.1)
Create a simple input form and press create to register information
In the case of ** form_for **, implement with the following description
= form_for @target do |f|
abridgement
= f.submit "Create"
Rewrite this and change to ** form_with ** with the following description
= form_with model: @target do |form|
abridgement
= f.submit "Create"
It may be natural for people who are accustomed to writing, but the page transition (redirect_to) when submit is pressed does not work. The data is saved, but the same content propagates because you can press create many times. process of create
def create
@target = Target.new(target_params)
if @target.save
redirect_to root_path
else
render :new
end
end
For the time being, binding.pry → It stopped, so it works normally. save
def create
@target = Target.new(target_params)
if @target.save
binding.pry
redirect_to root_path
else
render :new
end
end
Pattern 2, binding.pry → It stopped, but it should not stop if redirect_to is working. I guess redirect_to isn't working.
def create
@target = Target.new(target_params)
if @target.save
redirect_to root_path
binding.pry
else
render :new
end
end
All you have to do is search on google.
Caused by missing option in form_with. The following is a description to make it work.
= form_with model: @target, local: true do |form|
abridgement
= f.submit "Create"
As a cause, form_with sends form by ajax communication. When you send a form using that ajax, turbolinks is involved in the behavior of redirect_to executed by the destination controller. And it seems that it didn't work because I didn't put turbolinks.
There are two solutions, and I added local: true to disconnect ajax communication by either introducing turbolinks or disconnecting ajax communication.
The content was that I felt like I learned it at school, but when I experienced it, I forgot. .. .. Since this is my first time posting an article, I would appreciate it if you could let me know if there are any etiquette violations, misinterpretations, or improvements.
Thank you very much.
Recommended Posts