仅验证嵌套属性rails的前两个构建对象title属性

时间:2018-06-04 11:29:35

标签: ruby ruby-on-rails-4 ruby-on-rails-5 nested-attributes

我正在为课程构建4个学习目标对象,这些对象接受选项作为嵌套属性。我想只验证学习目标的前两个标题值,而2应该是可选的,即如果空白则拒绝。

class Course < ApplicationRecord
    has_many :learning_objectives
    accepts_nested_attributes_for :learning_objectives
end

class LearningObjective < ApplicationRecord
   belongs_to :course
   validates_presence_of :title
end

如何仅验证前2个构建的对象?

1 个答案:

答案 0 :(得分:2)

添加custom validation method,例如:

class Course < ApplicationRecord
  has_many :learning_objectives
  accepts_nested_attributes_for :learning_objectives

  MIN_LEARNING_OBJECTIVES = 2
  MAX_LEARNING_OBJECTIVES = 4

  validate :learning_objectives_count_in_range

  private

  def learning_objectives_count_in_range
    objectives_count = learning_objectives.count
    return if objectives_count.between?(MIN_LEARNING_OBJECTIVES, MAX_LEARNING_OBJECTIVES)

    errors.add(:base, "must have between #{MIN_LEARNING_OBJECTIVES} and #{MAX_LEARNING_OBJECTIVES} learning objectives")
  end
end