本文介绍了验证 rails 中多个属性之一的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在多语言应用程序中,用户可以输入他们的中文和英文名称.用户可以输入一个或两个,但必须至少输入一个名称.
In an multilingual application, a user can input their Chinese and English names. The user can input either or both, but must input at least one name.
class Person < ActiveRecord::Base
validates :zh_name, :presence => true
validates :en_name, :presence => true
validates :fr_name, :presence => true
end
由于内置的 :validates_presence_of 方法只能同时验证两个属性,有没有办法验证 rails 中至少一个属性的存在?
Since the built-in :validates_presence_of method can only validate both attributes at once, is there a way to validate the presence of at least one of many attributes in rails?
就像一个魔法,validates_one_of :zh_name, :en_name, :fr_name
先谢谢你,
推荐答案
validate :at_least_one_name
def at_least_one_name
if [self.zh_name, self.en_name, self.fr_name].reject(&:blank?).size == 0
errors[:base] << ("Please choose at least one name - any language will do.")
end
end
这篇关于验证 rails 中多个属性之一的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!