If you get stuck in validation when submitting form content
Render the new post screen with the render
method
There should be many people who learned by displaying the error or the content that was entered.
But what if you can't use the render
method?
Actually, I'm using the Google Map API for my portfolio.
When rendering a page with render
, there is a problem that MAP is not displayed for some reason ...
It was a problem that could be solved by changing the specifications, but I didn't want to change it.
I will show you how to achieve the above movement without using render
.
As an example in tasks_controller.rb
The action new
on the new post page and
Suppose you have an action create
that saves new posts.
tasks_controller.rb
def create
@task = Task.new(task_params)
if @task.save
redirect_to @task, notice: 'You have saved the task.'
else
render :new
end
end
@ task.save
fails and render: new
under ʻelseis executed, The new post page will be rendered. After that, as you already know, it feels like using
@ task.errors.full_messages` in the view.
It takes the form of re-accessing with redirect_to
Error statements and input contents are stored in flash
in the action.
tasks_controller.rb
def create
@task = Task.new(task_params)
if @task.save
redirect_to @task, notice: 'You have saved the task.'
else
flash[:error_msgs] = @task.errors.full_messages
flash[:tmp_body] = @task.body
redirect_to new_task_url
end
end
An error statement in flash [: error_msgs]
The text contents are stored in flash [: tmp_body]
.
After that, it is OK if you use the value of flash in the access destination view. that's all!
Recommended Posts