'Rails: Validation error messages are not displayed
I am new to rails, trying to learn by creating a simple test project where I am trying to display validation error messages on my browser. The problem is that the messages are not getting displayed. I am referring to this blog
#app/controller/dogs.rb
def create
@dog = Dog.new(dog_params)
if @dog.save
redirect_to dog_path(@dog)
else
p @dog.errors.inspect
render :new
end
end
# app/models/dog.rb
class Dog < ApplicationRecord
validates :name, presence: true
validates :age, presence: true
end
<!-- app/views/dogs/new.html.erb -->
<h1>CREATE NEW PUP!</h1>
<%= @dog.errors.inspect %>
<% if @dog.errors.any? %>
<% @dog.errors.full_messages.each do |message|%>
<h3><%= message %></h3>
<% end %>
<% end %>
<br />
<%= form_for @dog do |f| %>
<%= f.label :NAME %>
<%= f.text_field :name %>
<%= f.label :AGE%>
<%= f.text_field :age%>
<br />
<%= f.submit "SUBMIT" %>
<% end %>
I have 2 observations:
- If I go to the networks DevTool in chrome and then check the preview tab, I can see that the error messages are being rendered in the preview tab. But I can't see them on the main browser/output. Tried with multiple browsers. Same result.
- Upon printing
@dog.errors.inspectfrom the controller to the terminal, I can see the errors. But when using@dog.errors.inspecton the view, the errors[] is empty.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
