嗨,我正在构建一个简单的应用程序,当有人在字段中输入无效信息或根本没有信息时,无法显示错误消息。
我使用的表单是注册一个新用户,与用户和表单相关的代码如下;
users_controller.rb
Class UsersController < ApplicationController
def index
@users = User.all
end
def show
@user = User.find(params[:id])
@country = Country.all
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to @user
else
redirect_to '/signup'
end
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password)
end
end
用户.rb
class User < ApplicationRecord
before_save { self.email = email.downcase }
validates :first_name, presence: true, length: { maximum: 25 }
validates :first_name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }
has_many :trips
has_many :countries, through: :trips
end
新的.html.erb
<div class="container">
<h1 class="text-center">Sign up</h1>
<div class="row">
<div class="col-md-6 offset-md-3 ">
<%=form_for(@user) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :first_name %>
<%= f.text_field :first_name, class: "form-control" %>
<%= f.label :last_name %>
<%= f.text_field :last_name, class: "form-control" %>
<%= f.label :email %>
<%= f.email_field :email, class: "form-control" %>
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
<%= f.submit "Create an account", class: 'form-control btn btn-primary' %>
<% end %>
</div>
</div>
</div>
_error_messages.html.erb
<% if @user.errors.any? %>
<div class="alert alert-danger">
The form contains <%= pluralize(@user.errors.count, "error") %>.
</div>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% else %>
<h3>test</h3>
<% end %>
当我加载表单时,我确实看到了“测试”字符串,我把它放在我的 _error_messages.html.erb 中以供查看。但是,当我在注册页面中输入数据时,它会重新加载页面(因为它应该在所有字段都有效时将其发送到用户页面)。但是,“Test”字符串仍然出现在顶部,而不是应该出现的错误消息。
我的假设是我需要某种会话或某些东西来记住错误是什么,因为现在它重新加载了一个全新的页面,内存中没有任何内容,但是,我目前无法在任何地方找到解决方案。
任何帮助将非常感激!