在多语言应用程序中,用户可以输入他们的中文和英文名称。用户可以输入其中一个或两个,但必须至少输入一个名称。
class Person < ActiveRecord::Base
validates :zh_name, :presence => true
validates :en_name, :presence => true
validates :fr_name, :presence => true
end
由于内置:validates_presence_of方法只能同时验证两个属性,有没有办法验证rails中至少有一个属性存在?
就像一个神奇的,validates_one_of :zh_name, :en_name, :fr_name
提前谢谢你,
答案 0 :(得分:33)
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
答案 1 :(得分:11)
让@ micapam进一步回答,我可以建议:
validate :has_a_name
def has_a_name
unless [zh_name?, en_name?, fr_name?].include?(true)
errors.add :base, 'You need at least one name in some language!'
end
end
答案 2 :(得分:2)
validates :zh_name, :presence => { :if => (fr_name.blank? && en_name.blank?) }
答案 3 :(得分:2)
validate :has_a_name
def has_a_name
unless [zh_name, en_name, fr_name].any?{|val| val.present? }
errors.add :base, 'You need at least one name in some language!'
end
end
Max Williams的回答很好,但是我没有看到有必要计算命中率吗?返回一个布尔值。