2009-08-13 25 views
0

目前我想顯示我的錯誤,我同時添加到用戶對象控制器內我的模型內部驗證顯示。我如何保存錯誤在模型內部的容器,並在控制器

好像如果我的控制器中有錯誤,立即顯示它然後返回並且不顯示模型內的錯誤,我知道如果我的錯誤完成計數並顯示所有錯誤,一。

我甚至寫了應檢查模型內部的驗證,並將它們保存到我的對象則顯示錯誤的方法可以顯示所有的錯誤,包括驗證方法是在模型中發現了一個人的。

我控制器的方法是這樣的

def info 

    if @user.firstname != "" && @user.lastname != "" && @user.id_number != "" && @user.email != "" 
    @user.errors.add_to_base("Password can't be blank") 
    end 

end 



def validations() 
    @errors = User.check_validations 
end 

def display(template_to_render) 
    if @user.errors.count >= 1 
    render :action => template_to_render 
    end 
end 

然後我在模型方法如下

def self.check_validations 
    validates_presence_of :firstname, :lastname, :date_of_birth, :if => Proc.new { |o| o.force_update? || o.profile_confirmed? } 
end 

的話,我想驗證方法的所有錯誤添加到@ user.errors.to_base錯誤 ,並顯示它們。

,所以我想知道是否有任何方法也許我可以用它來檢查模型內部的方法,而且所有這些錯誤添加到@user對象纔可以在該視圖中顯示。

回答

1

一對夫婦的事情。

  1. 所有驗證應該在模型中,你不應該在控制器中調用errors.add

  2. validates_presence_of是一個類的方法,其限定應該發生的驗證。驗證不會發生在這個確切點上。因此,您不能在每個請求的基礎上使用它。

如果您只想進行一次驗證,然後稍後再驗證模型的其餘部分,請嘗試此操作。

class User < ActiveRecord::Base 
    validate :check_password 
    validates_presence_of :firstname, :lastname, :date_of_birth, :if => Proc.new { |o| o.force_update? || o.profile_confirmed? } 

    def check_password 
    if firstname != "" && lastname != "" && id_number != "" && email != "" 
     errors.add_to_base("Password can't be blank") 
    end 
    end 
end 

然後,您可以直接調用check_password以僅在需要時驗證。

def info 
    @user.check_password 
end 

def validations 
    @user.valid? # triggers validations 
    @errors = @user.errors 
end 

def display(template_to_render) 
    if @user.errors.count >= 1 
    render :action => template_to_render 
    end 
end 

我假定這些方法都稱爲一個請求,他們不是每個單獨的控制器動作。

0

你在「self.check_validations」中所做的是在你的控制器每次運行時添加驗證。 1000個請求後,您將有1000個驗證添加到模型和崩潰的應用程序(可能)。

查找在Rails的文檔「有條件驗證」,這將解釋如何實現你想要什麼。

您也可以調查.save!和.create!你在哪裏得到的例外,如果該模型是無效的方法 - 這可以讓你改變一個更明確的方式控制流

相關問題