Vir*_*ren 6 validation ruby-on-rails ruby-on-rails-3 rails-3.1 ruby-on-rails-3.2
我想在自定义验证中应用范围限制器
我有这个产品模型,它有make,model,serial_number,vin作为属性
现在我有一个自定义验证来检查vin如果vin不存在,以检查数据库中make + model + serial_number唯一性的组合
validate:combination_vin,:if =>"vin.nil?"
def combination_vin
if Product.exists?(:make => make,:model => model,:serial_number => serial_number)
errors.add(:base,"The Combination of 'make+model+serial_number' already present")
end
end
Run Code Online (Sandbox Code Playgroud)
我想在此验证器中针对user_id引入一个范围
现在我知道我可以轻松地写这个以实现相同的使用
def combination_vin
if Product.exists?(:make => make,:model => model,:serial_number => serial_number,:user_id => user_id)
errors.add(:base,"The Combination of 'make+model+serial_number' already present")
end
end
Run Code Online (Sandbox Code Playgroud)
但出于好奇,我想在自定义验证上有一个范围验证器(类似{:scope =>:user_id}),这样我就不必在存在中传递额外的user_id了吗?哈希
谢谢
试试:
validate :combination_vin , :uniqueness => { :scope => :user_id } , :if => "vin.nil?"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1574 次 |
| 最近记录: |