嗨我有一个简单的应用程序,我正在构建,并且遇到有人输入无效信息或根本没有信息到字段时出现错误消息出现问题。窗体错误消息不生成Rails应用程序
我正在使用的表单是注册一个新用户,与用户和表单关联的代码如下所示;
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
user.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+\-.][email protected][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
new.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”字符串仍然出现在顶部,而不是应该出现的错误消息。
我的假设是我需要某种会话或某些东西来记住错误是什么,因为现在它重新加载了一个全新的页面,内存中没有任何内容,但是,目前我无法在任何地方找到解决方案。
任何帮助将不胜感激!
尝试将'redirect_to'/ signup''更改为'render'new'' – Pavan
谢谢@Pavan工作!你能解释两种表述之间的区别吗? –
我已经添加了我的答案并解释了其中的差异。希望你觉得它有帮助:) – Pavan