验证Rails中的属性集合

时间:2014-06-04 18:01:30

标签: ruby-on-rails validation

我正在寻找一种解决方案来验证属性集合中是否存在至少一个属性。在我的模型中,我有一系列属性的常量:

LANGUAGES = [:eng, :spanish, :german, :italian, etc]

然后我在视图中迭代它,将每个属性设置为一个复选框。我需要确保至少选中一个复选框才能使表单有效。这是我目前的自定义验证方法,但由于某种原因它无效:

validate : validate_languages

private
def validate_languages
  LANGUAGES.each do |primary_language|
    language = self.send(primary_language)
    if self.language.blank?
      self.errors.add(:language, "You must select at least one option.")
    end
  end
end

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

validates :language, presence: true, inclusion: { in: LANGUAGES }

或重新发明轮子:

validate :language_integrity

def language_integrity
  self.errors.add(:language, "Language can't be blank!") if self.language.blank?
  self.errors.add(:language, "Language is not standard") unless LANGUAGES.includes?(self.language.to_sym)
end

在您对此答案发表第一条评论后,您可以:

validate :language_integrity

def language_integrity
  LANGUAGES.each do |language|
    return true if self.send(language).present?
  end
  self.errors.add(:language, "Select at least one Language!")
end