Ruby on rails 3 如何根据类的多个属性编写RubyonRails验证?
假设我有一个具有3个属性的模型类。我想确保三个人中至少有一个在场Ruby on rails 3 如何根据类的多个属性编写RubyonRails验证?,ruby-on-rails-3,validation,Ruby On Rails 3,Validation,假设我有一个具有3个属性的模型类。我想确保三个人中至少有一个在场 我必须为此编写自定义验证吗?或者,有没有一种方法可以通过现有的验证帮助程序来实现这一点?您需要为此编写一个自定义验证程序。您只需将ActiveModel::Validator子类化并实现validaterecord方法,该方法在发生错误时会添加到记录的错误哈希: class YourValidator < ActiveModel::Validator def validate(record) if (
我必须为此编写自定义验证吗?或者,有没有一种方法可以通过现有的验证帮助程序来实现这一点?您需要为此编写一个自定义验证程序。您只需将ActiveModel::Validator子类化并实现validaterecord方法,该方法在发生错误时会添加到记录的错误哈希:
class YourValidator < ActiveModel::Validator
def validate(record)
if (your_failure_condition_here)
record.errors[:base] << "Your error message"
end
end
end
在我看来,在您的模型中进行自定义验证是最干净的方式:
class Model
validate :at_least_one_present
def at_least_one_present
if(they_dont_exist)
errors.add("need at least one of these fields")
end
end
end
参考:
class Model
validate :at_least_one_present
def at_least_one_present
if(they_dont_exist)
errors.add("need at least one of these fields")
end
end
end