我是 Rails 新手,尝试通过创建一个简单的测试项目来学习,在该项目中我尝试在浏览器上显示验证错误消息。问题是消息没有显示。我指的是这个博客
#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 %>
我有两个观察结果:
@dog.errors.inspect
到终端后,我可以看到错误。但是当在视图上使用 @dog.errors.inspect
时,errors[] 为空。也许可以帮助别人,要解决这个问题只需使用:
渲染“新”,状态::unprocessable_entity