轨道3验证模型
问题描述:
的实例方法我想打电话给活动记录验证方法在我的自定义的验证方法,像轨道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>
我们如何可以调用实例方法验证方法的模型
答
可能是您正在使用Rails(3.xx)(rails -v)的新版本,但您仍然拥有旧的Rails应用程序...您应该在另一个文件夹中生成Rails应用程序,然后移动您的文件.rb ,视图等在您的新应用程序/文件夹... 我确认“验证是唯一的3,通常当发生错误,人仍然在2.3”像a3uge说。
答
您可以实例化一个特定的验证,并调用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
这可能是解决不了问题的,但你确定你使用Rails 3?验证对于3是唯一的,通常当发生错误时,人们仍然在2.3。 – a3uge 2011-04-14 17:59:28
是的,我在轨道上3轨-v =>轨道3.0.4 – Naveed 2011-04-15 04:22:22
使用“validates_uniqueness_of:标识符”,而不是一个before_validation过滤器为您的自定义代码。 – jvatic 2011-04-16 01:08:03