rails7でバリデーションエラーで画面が遷移しない場合の解決法
環境
Ruby 3.0.2
Rails 7.0.2.3
結論:Turboの動作をオフにする
form_withに data: { turbo: false }
を追加する
new.html.haml (≒ new.html.erb)
= form_with model: @event, data: { turbo: false } do |f|
= f.label :name, 'イベント名'
= f.text_field :name
発生したエラー
バリデーションエラーが発生した際に、画面のリロードが発生せず、コンソールに以下のエラーが表示された。
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を実現してくれる
参考
Author And Source
この問題について(rails7でバリデーションエラーで画面が遷移しない場合の解決法), 我々は、より多くの情報をここで見つけました https://qiita.com/yasuhiron777/items/b66e3205d6739d7f7ede著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .