0

I have a simple example where I'm trying to show validation errors in a rails form, but for some reason I can see the errors in dev tools "Preview" but not in the app itself (see screenshot). I've been reading every thread I can but unsure why I'm experiencing this issue:

models/user.rb

# == Schema Information
#
# Table name: users
#
#  id              :bigint           not null, primary key
#  first_name      :string
#  last_name       :string
#  email           :string
#  password_digest :string
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#
class User < ApplicationRecord
  has_secure_password

  validates :first_name, :last_name, :email, presence: true
  validates_uniqueness_of :email
end

controllers/users_controller.rb

class UsersController < ApplicationController
  def new
    @user = User.new
  end
  
  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to dashboard_index, notice: "Thanks for signing up!"
    else
      render :new
    end
  end

  private
  def user_params
    params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)
  end
end

views/users/new.html.erb

<h1>Sign Up</h1>
<%= form_with(model: @user, local: true) do |f| %>
  <%= @user.errors.inspect %>
  <p><%= @user.errors.any? %></p>
  <% if @user.errors.any? %>
    <div>
      <ul>
        <% @user.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :first_name %><br />
    <%= f.text_field :first_name %>
  </div>
  <div class="field">
    <%= f.label :last_name %><br />
    <%= f.text_field :last_name %>
  </div>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </div>
  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %>
  </div>
  <div class="actions"><%= f.submit "Sign Up" %></div>
<% end %>

Image

errors showing in preview but not in dom

dbugger
  • 15,868
  • 9
  • 31
  • 33
twknab
  • 1,741
  • 1
  • 21
  • 35
  • 3
    https://stackoverflow.com/a/71762032/207090 – Alex Jul 27 '23 at 16:27
  • @Alex you are a hero and a scholar my friend. Thank you this was such a trivial thing I was getting into the weeds on. Resolved by changing `render :new` to `render :new, status: :unprocessable_entity` – twknab Jul 27 '23 at 21:09

0 Answers0