0

Делаю регистрацию пользователя и обработку ошибок. Возникла проблема, что по нажатию submit с неверно заполненными данными ошибки не показываются.

Что я упустил? Что надо сделать?

Заметил, что в Network вкладке приходит response html с ошибками и тд. Если я правильно понял, то по нажатию submit рельсы должны изменить html полученный из response.

Модель юзера:

class User < ApplicationRecord
  has_secure_password

  validates :email, presence: true, uniqueness: true
  validates :name, presence: true, uniqueness: true
end

controller

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new user_params
    if @user.save
      flash[:success] = "Welcome, #{@user.name}!"
      redirect_to '/'
    else
      render :new
    end
  end

  private

  def user_params
    params.require(:user).permit(:email, :name, :password, :password_confirmation)
  end
end

new.html.erb

<% provide :page_title, 'Registration' %>

<h1>Registration</h1>

<%= render 'form' %>

_form.html.erb

<%= form_with(model: @user, local: true) do |f| %>
  <%= render 'shared/errors', resource: @user %>

  <p>
    <%= f.label :email %><br>
    <%= f.text_field :email %>
  </p>

  <p>
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </p>

  <p>
    <%= f.label :password %><br>
    <%= f.password_field :password %>
  </p>

  <p>
    <%= f.label :password_confirmation %><br>
    <%= f.password_field :password_confirmation %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

shared/errors

<% if resource.errors.any? %>
  <div style="color: red">
    <h2><%= pluralize(resource.errors.count, "error") %> prohibited this post from being saved:</h2>
    <ul>
      <% resource.errors.each do |error| %>
        <li><%= error.full_message %></li>
      <% end %>
    </ul>
  </div>
<% end %>

1 ответ 1

0

В rails 7 теперь используется по умолчанию turbo frames. И рендер формы надо поместить в такой фрейм.

<%= turbo_frame_tag "user" do %>
  <%= render 'form' %>
<% end %>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.