我正在回答我自己的问题 - 只是把它放在谷歌这里,以防它帮助其他人。此代码允许您验证列表中是否存在一个字段。请参阅代码中的注释以了解用法只需将其粘贴到lib / custom_validations.rb中,然后将“custom_validations”添加到您的environment.rb
#good post on how to do stuff like this http://www.marklunds.com/articles/one/312
module ActiveRecord
module Validations
module ClassMethods
# Use to check for this, that or those was entered... example:
# :validates_presence_of_at_least_one_field :last_name, :company_name - would require either last_name or company_name to be filled in
# also works with arrays
# :validates_presence_of_at_least_one_field :email, [:name, :address, :city, :state] - would require email or a mailing type address
def validates_presence_of_at_least_one_field(*attr_names)
msg = attr_names.collect {|a| a.is_a?(Array) ? " ( #{a.join(", ")} ) " : a.to_s}.join(", ") +
"can't all be blank. At least one field (set) must be filled in."
configuration = {
:on => :save,
:message => msg }
configuration.update(attr_names.extract_options!)
send(validation_method(configuration[:on]), configuration) do |record|
found = false
attr_names.each do |a|
a = [a] unless a.is_a?(Array)
found = true
a.each do |attr|
value = record.respond_to?(attr.to_s) ? record.send(attr.to_s) : record[attr.to_s]
found = !value.blank?
end
break if found
end
record.errors.add_to_base(configuration[:message]) unless found
end
end
end
end
end
答案 0 :(得分:14)
这在Rails 3中对我有用,虽然我只是在验证是否存在一个或另一个字段:
validates :last_name, :presence => {unless => Proc.new { |a| a.company_name.present? }, :message => "You must enter a last name, company name, or both"}
如果公司名称为空,则仅验证last_name的存在。您只需要一个,因为在错误条件下两者都是空白的,因此在company_name上有一个验证器也是多余的。唯一令人烦恼的是它在消息之前吐出了列名,我使用了this关于人化属性的问题的答案来绕过它(只是将last_name humanized属性设置为“”