我的模型上有一些活动记录验证:
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
end
看起来不错。它验证了
name
不是
nil
""
custom validation
,我要加上
validate
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
validate :name_must_start_with_abc
private
def name_must_start_with_abc
unless name.start_with?('abc')
self.errors['name'] << 'must start with "abc"'
end
end
end
问题是:当
名称
无
presence_of
name_must_start_with_abc
,提出
NoMethodError
是
.
为了克服这个问题,我必须在
def name_must_start_with_abc
return if name.nil?
unless name.start_with?('abc')
self.errors['name'] << 'must start with "abc"'
end
end
这就是我不想做的,因为如果我添加更多的“依赖”验证,我必须在每个自定义验证方法上重新验证它。
如何处理Rails上的依赖验证?有没有办法防止在其他验证未通过时调用自定义验证?