2011-04-14 140 views
4

的實例方法我想打電話給活動記錄驗證方法在我的自定義的驗證方法,像軌道3驗證模型

class Asset < ActiveRecord::Base 
    validate :ensure_unique_identification_code 
    validates :name,:uniqueness=>true 

def ensure_unique_identification_code 
    self.identifier="identifier code" #code is generated using some helper method of Asset model 
    validates :identifier ,:uniqueness=>true 

end 
end 

報錯

undefined method `validates' for #<Asset:0xb6692dbc> 

我們如何可以調用實例方法驗證方法的模型

+0

這可能是解決不了問題的,但你確定你使用Rails 3?驗證對於3是唯一的,通常當發生錯誤時,人們仍然在2.3。 – a3uge 2011-04-14 17:59:28

+0

是的,我在軌道上3軌-v =>軌道3.0.4 – Naveed 2011-04-15 04:22:22

+0

使用「validates_uniqueness_of:標識符」,而不是一個before_validation過濾器爲您的自定義代碼。 – jvatic 2011-04-16 01:08:03

回答

0

可能是您正在使用Rails(3.xx)(rails -v)的新版本,但您仍然擁有舊的Rails應用程序...您應該在另一個文件夾中生成Rails應用程序,然後移動您的文件.rb ,視圖等在您的新應用程序/文件夾... 我確認「驗證是唯一的3,通常當發生錯誤,人仍然在2.3」像a3uge說。

0

您可以實例化一個特定的驗證,並調用validate()方法直接:

def age_validation 
    ActiveModel::Validations::NumericalityValidator.new(
    :greater_than_or_equal_to => 0, 
    :less_than_or_equal_to => 100, 
    :attributes => :age 
).validate(self) 
end