繁体   English   中英

Ruby on Rails中未显示表单错误

[英]Form errors not showing in Ruby on Rails

我正在尝试使用Rails创建注册表。 它正在工作,但是不会显示验证中的错误(它会验证,但不会显示错误)。

这是我的文件:

# 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 %>

# 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

为什么不显示错误?

谢谢!!

您的表单POST操作应真正指向create方法,而新方法实际上仅是呈现表单。 我的意思是它与您的问题无关,但这是Rails约定。

您的问题的答案是,在尝试保存用户的分支中,需要将您的User对象设置为INSTANCE变量。 您只需将其作为局部变量即可。 因此,当表单呈现时,表单助手会在当前作用域中查找实例变量“ @user”,但它不存在。 在您尝试执行保存的分支的第二部分中,在用户变量前面放置一个“ @”。 如果失败,则表单助手应显示错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM