When submitting form, no error message is displayed even though validation failed

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.

Wrong code

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

Cause

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

When submitting form, no error message is displayed even though validation failed
No error message is displayed when create action fails
When an error occurs even though validation is not set
The devise error message is not displayed properly.
When using Map for form in Spring, order is not guaranteed when submitting even LinkedHashMap
[Note] Error message when using Rails Form object pattern Japanese
[Rails] Japanese localization of error message when using Form object