railsでバリデーションエラーが表示されない
Rails 7.0.4
railsでバリデーションエラーが表示されなくて困った困った。
下記で自分の思う限りでは記載したはずなのにエラーが出ない、、、。
どうすればいいのかと2~3時間も時間を費やしてしまった。
原因はstatus: :unprocessable_entity
をつけないといけないようになってるようです。
Rails 7からは追記が必要らしいです。
def update if @product.update(product_params) redirect_to admin_products_path(@product), notice: 'Product was successfully updated.' else render :edit, status: :unprocessable_entity end end
admin/products_controller.rb
# frozen_string_literal: true module Admin class ProductsController < ApplicationController before_action :basic_auth before_action :set_product, only: %i[update edit destroy] def index @products = Product.all end def new @product = Product.new end def update if @product.update(product_params) redirect_to admin_products_path(@product), notice: 'Product was successfully updated.' else render :edit end end def create @product = Product.new(product_params) @product.save ? redirect_to(admin_products_path) : render(:new) end def edit; end def destroy @product.destroy redirect_to admin_products_path, notice: 'Product was successfully destroyed.' end private def set_product @product = Product.find(params[:id]) end def product_params params.require(:product).permit(:name, :description, :price, :image) end def basic_auth authenticate_or_request_with_http_basic do |username, password| username == 'admin' && password == 'pw' end end end end
edit.html.erb
<section class="py-5"> <%= form_with(model: @product, url: admin_product_path(@product), local: true) do |f| %> <%# <%= render partial: 'shared/error_messages', object: @product %> <%= render 'shared/error_messages', object: @product %> <div class="form-floating"> <%= f.text_area :name, class: 'form-control', id: 'floatingName', placeholder: 'Enter product name' %> <%= f.label :name, 'Name', for: 'floatingName' %> </div> <div class="form-floating"> <%= f.text_area :description, class: 'form-control', id: 'floatingDescription', placeholder: 'Enter product name' %> <%= f.label :description, 'Description', for: 'floatingDescription' %> </div> <div class="form-floating"> <%= f.number_field :price, class: 'form-control', id: 'floatingPrice', placeholder: 'Enter product price' %> <%= f.label :price, 'Price', for: 'floatingPrice' %> </div> <div class="form-floating"> <%= f.file_field :image, class: 'form-control', id: 'floatingImage' %> <%= f.label :image, 'Image', for: 'floatingImage' %> </div> <%= f.submit "更新", class: 'btn btn-primary' %> <% end %> </section>
_error_messages.html.erb
<% if object.errors.any? %> <div class="alert alert-danger"> <ul> <% object.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %>