我正在开发一个Rails3应用程序,它需要在虚拟字段上运行验证,以查看记录是否已经存在……以下是我的模型代码:
#mass-assignment
attr_accessible :first_name, :last_name, :dob, :gender
#validations
validates_presence_of :first_name, :last_name, :gender, :dob
validates :fullname, :uniqueness => { :scope => [:dob] }
def fullname
"#{first_name} #{last_name}"
end我没有得到任何错误,它通过了验证。
发布于 2012-07-31 09:47:44
我不认为你可以用标准的validates做这样的事情。原因是,它通常是一个“简单的”sql查询,以获得唯一性。但要检查从您的方法返回的内容的唯一性,它必须:
fullname方法。的唯一性时将每个结果添加到数组中
当数据集很小时很简单,但是一旦你的范围内达到10K以上的匹配,就需要很长时间才能做到。
我个人使用使用dob作用域的标准before_save来做这件事
before_save :check_full_name_uniqueness
def check_full_name_uniqueness
query_id = id || 0
return !Patient.where("first_name = ? and last_name = ? and dob = ? and id != ?", first_name, last_name, dob, query_id).exists?
end添加错误消息(在返回之前):
errors.add(:fullname, 'Your error')回到控制器中,获取错误:
your_object.errors.each do |k, v| #k is the key of the hash, here fullname, and v the error message
#Do whatever you have to do
endhttps://stackoverflow.com/questions/11731894
复制相似问题