1

I have implemented following validation on my model-class:

class Department < ApplicationRecord
  has_many :employees, dependent: :destroy

  validates :name, presence: true, length: { minimum: 3, maximum: 50 }
end

It works fine. It isn't possible anymore to create Department-objects without providing a name.

But in my template there are no errors available.

Error-Messages: <%= @department.errors.full_messages.size %>
<% if @department.errors.any? %>
  <% @department.errors.full_messages.each do |message|%>
     <h3><%= message %> </h3>
  <% end %>
<% end %>
<%= render "form", department: @department %>

The error-messages debug-output shows always 0.

My controller-code:

   def new
     @department = Department.new
   end

  def create
    @department = Department.create(department_params)

    if @department.save
      puts "-- Positive --"
      redirect_to departments_path
    else
      puts "-- Negative --"
      puts @department
      puts @department.errors.full_messages
      puts "Error message: #{@department.errors.full_messages.size}"
      puts " ------------ "
      render :new
    end
  end

Output:

-- Negative --
#<Department:0x0000000109b59398>
Name can't be blank
Name is too short (minimum is 3 characters)
Error message: 2
 ------------ 

Means: In the controller is everything as expected. But in the view-template errors is empty (size 0).

What goes wrong here? How can it be fixed?

2
  • @Alex That did it. Thanks a big bunch. I you want, then turn your comment to an answer. I will accept it. Commented Jun 9, 2024 at 7:09
  • 1
    You should be using @department = Department.new(department_params) and not .create which will insert the record. Rails won't actually do two queries but you're laying a trap for yourself if you want to manipulate the record before saving at a later point. Commented Jun 10, 2024 at 13:27

1 Answer 1

1

You have to specify status 422 to let Turbo know that you're rendering an error page, otherwise, it expects a redirect after a form submission:

render :new, status: :unprocessable_entity

You can also see the error message from Turbo in browser console.

https://turbo.hotwired.dev/handbook/drive#redirecting-after-a-form-submission

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.