gpt4 book ai didi

ruby-on-rails - 如何验证多个字段中的一个字段是否存在

转载 作者:行者123 更新时间:2023-12-03 00:47:57 24 4
gpt4 key购买 nike

我正在回答我自己的问题 - 只是将其放在这里供 google-fu 以防对其他人有所帮助。此代码允许您验证列表中某个字段是否存在。使用方法请参见代码中的注释。只需将其粘贴到 lib/custom_validations.rb 并将 require 'custom_validations' 添加到您的环境中。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

最佳答案

这在 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"}

如果公司名称为空,则仅验证姓氏是否存在。您只需要其中一个,因为在错误情况下两者都将为空白,因此在 company_name 上也有一个验证器是多余的。唯一烦人的是它在消息之前吐出列名,我使用了 this 中的答案关于人性化属性的问题来解决它(只需将last_name人性化属性设置为“”

关于ruby-on-rails - 如何验证多个字段中的一个字段是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1835393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com