LoginSignup
2
3

More than 1 year has passed since last update.

rails7でバリデーションエラーで画面が遷移しない場合の解決法

Last updated at Posted at 2022-04-01

バリデーションエラーが起きた後、画面遷移せずにエラーメッセージも表示されなかったのでこれを解決するしました。

環境

Ruby 3.0.2
Rails 7.0.2.3

結論:Turboの動作をオフにする redirect_toを使う

form_withに data: { turbo: false } を追加する

render :new としていた部分を redirect_to action: :newに変更したら解決しました。
バリデーションエラーはflashを使って取得しています。

EventsController.rb
  def create
    @event = events.new(event_params)
    if @event.save
      flash[:success] = "#{@event.name}を登録しました"
      redirect_to @event
    else
      flash[:errors] = @event.errors.full_messages
      redirect_to action: :new
      # render :new だと動かない
    end
  end

発生していたエラー

バリデーションエラーが発生した際に、画面のリロードが発生せず、コンソールに以下のエラーが表示された。

Error: Form responses must redirect to another location at k.requestSucceededWithResponse

問題発生時のコード

new.html.haml (≒ new.html.erb)
= form_with model: @event do |f|
  = f.label :name, 'イベント名'
  = f.text_field :name
Event.rb
class Event < ApplicationRecord
  has_many :items
  belongs_to :user

  validates :name, presence: true
EventsController.rb
class EventsController < ApplicationController
  before_action :authenticate_user!

  def new
    @event = Event.new
  end

  def create
    @event = current_user.events.new(event_params)
    if @event.save
      redirect_to action: :index
    else
      render :new
    end
  end

private

  def event_params
    params.require(:event).permit(:name, :event_datetime, :memo)
  end
...

Turboって?

rails7からデフォルトで入っているGem

ざっくりですが、Javascriptを書かずに簡単にSPAを実現してくれる

参考

2
3
2

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
2
3