Ruby on rails RubyonRails中未显示表单错误
我正在尝试使用Rails创建一个注册表。它正在工作,但不显示验证中的错误(它进行验证,但不显示错误) 这是我的档案:Ruby on rails RubyonRails中未显示表单错误,ruby-on-rails,ruby,forms,Ruby On Rails,Ruby,Forms,我正在尝试使用Rails创建一个注册表。它正在工作,但不显示验证中的错误(它进行验证,但不显示错误) 这是我的档案: # new.html.erb <h1>New user</h1> <% form_for :user, :url =>{:action=>"new", :controller=>"users"} do |f| %> <%= f.error_messages %> <p> <%=
# new.html.erb
<h1>New user</h1>
<% form_for :user, :url =>{:action=>"new", :controller=>"users"} do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :password %><br />
<%= f.password_field :password %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', users_path %>
#new.html.erb
新用户
{:action=>“new”,:controller=>“users”}do | f |%>
#user.rb
类用户
#用户_controller.rb
类UsersController“index”,:controller=>“users”)的url
其他的
呈现:操作=>“新建”
结束
结束
否则#用户已登录
flash[:notice]=“您已经注册了。”
将_重定向到(:action=>“index”)的url_
结束
结束
#删除了其他一些操作。。。。
结束
为什么不显示错误
谢谢 表单后期操作应该真正指向create方法,新方法实际上只是渲染表单。我的意思是这与你的问题无关,但这是Rails的惯例
问题的答案是,在尝试保存用户的分支中,需要将用户对象作为实例变量。你只需要把它作为一个局部变量。因此,当表单呈现时,表单帮助器在当前范围内查找实例变量“@user”,但它不存在。在分支的第二部分中的用户变量前面放一个“@”,在该部分中尝试保存。如果失败,那么表单帮助器应该显示错误。表单POST操作应该真正指向create方法,新方法实际上只是渲染表单。我的意思是这与你的问题无关,但这是Rails的惯例 问题的答案是,在尝试保存用户的分支中,需要将用户对象作为实例变量。你只需要把它作为一个局部变量。因此,当表单呈现时,表单帮助器在当前范围内查找实例变量“@user”,但它不存在。在分支的第二部分中的用户变量前面放一个“@”,在该部分中尝试保存。如果失败,那么表单帮助器应该显示错误
# user.rb
class User < ActiveRecord::Base
validates_presence_of :name
validates_presence_of :password
end
#users_controller.rb
class UsersController < ApplicationController
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def new
if session[:user_id].nil?
if params[:user].nil? #User hasn't filled the form
@user = User.new
else #User has filled the form
user = User.new(params[:user])
if user.save
user.salt = rand(1000000000)
user.password = Digest::MD5.hexdigest(user.salt.to_s + user.password)
user.save
flash[:notice] = 'User was successfully created.'
session[:user_id] = user.id
session[:password] = user.password
redirect_to url_for(:action=>"index",:controller=>"users")
else
render :action=>"new"
end
end
else #User is already logged in
flash[:notice] = 'You are already registered.'
redirect_to url_for(:action=>"index")
end
end
# some other actions removed....
end