0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】バリデーションのエラーメッセージが表示されない時

Posted at

controllerにstatus: :unprocessable_entityを追加

post_controller
  def update
    @post = Post.find_by(id: params[:id])
    @post.content = params[:content]
    if @post.save
      redirect_to("/posts/index")
    else
      render("posts/edit", status: :unprocessable_entity)
      # rails7系でバリデーションエラー文を表示させるには、 ,status: :unprocessable_entityの追記が必要)
    end
  end

Rails7.0からデフォルトでTurboが導入されており、バリデーションのエラーメッセージを表示させるためにはstatus: :unprocessable_entityの記述を追加する必要がある。

edit.html.erb
<div class="main posts-new">
  <div class="container">
    <h1 class="form-heading">編集する</h1>
    <%= form_tag("/posts/#{@post.id}/update") do %>
     <div class="form">
       <div class="form-body">
          <% @post.errors.full_messages.each do |message| %>
            <div class="form-error">
              <%= message %>
            </div>
          <% end %>
         <textarea name="content"><%= @post.content %></textarea>
         <input type="submit" value="保存">
       </div>
     </div>
    <% end %>
  </div>
</div>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?