在rails上的ruby中验证至少一个

时间:2015-02-26 17:14:45

标签: ruby-on-rails ruby

我正在尝试创建验证,因此至少选择了我拥有的6个选项的提供商。

我正在尝试使用它:

validate :at_least_one_provider
def at_least_one_provider
  unless [ticket_provider_name, ticket_provider_name_2, ticket_provider_name_3, ticket_provider_name_4, ticket_provider_name_5, ticket_provider_name_6].any?{|val| val.present? }
    errors.add :base, 'You need at least one provider!'
  end
end

但似乎只有在我选择了第一个名称时才会起作用(然后错误没有出现)但是如果我选择例如提供者2而不是提供者1,我会看到错误。

我也为每个提供商尝试了类似的事情:

 validates :ticket_provider_name, presence: true, if: "!ticket_provider_name_2.blank? || !ticket_provider_name_3.blank? || !ticket_provider_name_4.blank? || !ticket_provider_name_5.blank? || !ticket_provider_name_6.blank?", length: {maximum: 255}

任何想法我怎样才能让它发挥作用?

谢谢

2 个答案:

答案 0 :(得分:0)

def at_least_one_provider
  unless ticket_provider_name || ticket_provider_name_2 ||  ticket_provider_name_3 || ticket_provider_name_4 || ticket_provider_name_5 || ticket_provider_name_6
    errors.add :base, 'You need at least one provider!'
  end
end

答案 1 :(得分:0)

使用compact删除所有nil元素,然后检查是否还有剩余值。具有至少一个非nil元素将导致非空数组并通过验证。

validate :at_least_one_provider
def at_least_one_provider
  # for clarity
  provider_names = [ticket_provider_name, ticket_provider_name_2, ticket_provider_name_3, ticket_provider_name_4, ticket_provider_name_5, ticket_provider_name_6]

  # remove nils and fail validation if nothing left
  if provider_names.compact.empty?
    errors.add :base, 'You need at least one provider!'
  end
end

修改

由于您使用的是表单输入,因此空白字段将为空字符串而不是nil。使用与上述相同的策略,删除空字符串而不是nils:

validate :at_least_one_provider
def at_least_one_provider
  # for clarity
  provider_names = [ticket_provider_name, ticket_provider_name_2, ticket_provider_name_3, ticket_provider_name_4, ticket_provider_name_5, ticket_provider_name_6]

  # remove blank strings and fail validation if nothing left
  if provider_names.reject(&:blank?).empty?
    errors.add :base, 'You need at least one provider!'
  end
end