2009-08-12 60 views
0

我試圖用Rails創建一個註冊表單。它正在工作,但它不顯示驗證中的錯誤(驗證,但錯誤不顯示)。在Ruby on 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 

爲什麼沒有顯示錯誤?

謝謝!

回答

6

您的表單POST操作應該確實指向create方法,新方法實際上只是呈現表單。我的意思是它旁邊的問題,但它是Rails約定。

您的問題的答案是,在您嘗試保存用戶的分支中,您需要讓您的用戶對象成爲INSTANCE變量。你只是把它當作一個局部變量。所以當表單呈現時,表單助手在當前作用域中查找實例變量「@user」,但它不存在。在你的分支的第二部分在你的用戶變量的前面加上一個「@」,你可以嘗試並保存。如果失敗,那麼表單助手應該顯示錯誤。

+0

謝謝!固定... – 2009-08-12 18:09:22