gmi*_*ile 2 validation ruby-on-rails
假设我们有一个模型,我们称之为文章。那里,我们有两列min和max。规则是:min不能大于或等于max。您如何解决这种自定义类型的验证?有任何想法吗?
更进一步,让我们假设我们有列character和made_of。任务是创建一个验证,该验证将有助于避免“字符=人类”和“ made_of =钢铁”时的情况。
是否有标准的例程来管理列之间的“形而上”冲突?
您可以使用validate定义自己的验证。例如:
class Article < ActiveRecord::Base
validate :min_greater_than_max, :humans_aint_made_of_steel
def min_greater_than_max
errors.add(:min, "can't be greater than max") if min > max
end
def humans_aint_made_of_steel
errors.add(:human, "can't be made of steel") if character == 'human' && made_of == 'steel'
end
end
Run Code Online (Sandbox Code Playgroud)