When I created a form using form_with in Ruby on Rails and submitted the input contents, I got caught in the validation of the model and it was rendered, but the error message that should be displayed did not appear, so that I will introduce the cause.
class PostsController < ApplicationController
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to root_path
else
@post = Post.new #I was calling new before rendering
render "new"
end
end
private
def post_params
params.require(:post).permit(:content)
end
end
The cause was that save failed and @post = Post.new was written before rendering. If there is an error message for @post, it will be displayed, but if you add Post.new to @post, it will return to the same state as before the error occurred, so the error message will be displayed. It was in a state where it was not done.
So I solved it by deleting one line. I don't think I would make such a mistake now, but ... It ’s a mistake I made when I started studying.
Recommended Posts