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?