我正在关注RailsSpace教程。我的错误表单始终显示。它永远在线!我不知道怎么让它消失。我知道使用@ user.errors.clear实际上会清除消息。我尝试在视图中使用它,但根本不显示任何错误消息。感谢您的帮助。
以下是错误表单代码:
<% if @user.errors.any? %>
<div id="errorExplanation">
<h2>Please fix the following <%= pluralize(@user.errors.count, "error") %>:</h2>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
这是我的控制器:
class UserController < ApplicationController
def index
@title = "NubeMart Hub!"
end
def register
@user = User.new
@title = "Register"
if request.post?
@user = User.create(ad_params)
end
if @user.save
flash[:notice]="User #{@user.screen_name} created!"
redirect_to :action=>"index"
end
end
def ad_params
params.require(:user).permit(:screen_name, :email, :password)
end
end
以下是我的观点:
<h2>Register</h2>
<%= form_for :user do |form| %>
<%= render "shared/form_errors", :user => @user %>
<fieldset>
<legend>Enter Your Details</legend>
<div class="form_row">
<label for="screen_name">Screen name:</label>
<%= form.text_field :screen_name,
:size => User::SCREEN_NAME_SIZE,
:maxlength => User::SCREEN_NAME_MAX_LENGTH %>
</div>
<div class="form_row">
<label for="email">Email:</label>
<%= form.text_field :email,
:size => User::EMAIL_SIZE,
:maxlength => User::EMAIL_MAX_LENGTH %>
</div>
<div class="form_row">
<label for="password">Password:</label>
<%= form.password_field :password,
:size => User::PASSWORD_SIZE,
:maxlength => User::PASSWORD_MAX_LENGTH %>
</div>
<div class="form_row">
<%= submit_tag "Register!", :class => "submit" %>
</div>
</fieldset>
<% end %>
答案 0 :(得分:0)
您的注册方法有误:
def register
@user = User.new
@title = "Register"
if request.post?
@user = User.create(ad_params)
end
if @user.save # <== This block should be moved!
flash[:notice]="User #{@user.screen_name} created!"
redirect_to :action=>"index"
end
end
即使请求未发布,此代码if @user.save
也会执行。您已将此代码放在if if request.post?
之外。
我认为以下代码可以解决您的问题。
def register
@title = "Register"
if request.post?
@user = User.new(ad_params) # I have changed create to new
if @user.save # here your user will be saved(inly in case of post request)
flash[:notice]="User #{@user.screen_name} created!"
end
else
@user = User.new # (this is when request is not post)
end
redirect_to :action=>"index"
end