自定义验证导致其他验证失败

时间:2015-09-04 18:27:22

标签: ruby-on-rails

标题几乎解释了这个问题。

以下是我对我的模型的验证:

class Lesson < ActiveRecord::Base
  belongs_to :school
  has_many   :users, through: :goals
  has_many   :goals, dependent: :destroy

  validates :school_id, presence: true
  validates :date, presence: true, uniqueness: { scope: :school_id }
  validates :attendance, numericality: { only_integer: true,
                                         greater_than: 0 },
                         presence: true, if: :finished?
  validates :lesson_plan_week_number, numericality: { only_integer: true,
                                                      greater_than: 0 },
                                      presence: true, if: :finished?
end

我的所有模型测试(除了处理自定义验证的测试之外)都传递了上面的代码

然后我添加了validate :motion_presence和以下私有方法:

def motion_validation
  if debate?
    errors.add(:motion, "must be present if a debate was held")
  else
    errors.add(:motion, "cannot be present if a debate was held")
  end
end

现在曾经过的测试都失败了。发生了什么?

如果我组织错误

,请参阅模型中的相关代码
class Lesson < ActiveRecord::Base
  belongs_to :school
  has_many   :users, through: :goals
  has_many   :goals, dependent: :destroy

  validates :school_id, presence: true
  validates :date, presence: true, uniqueness: { scope: :school_id }
  validates :attendance, numericality: { only_integer: true,
                                         greater_than: 0 },
                         presence: true, if: :finished?
  validates :lesson_plan_week_number, numericality: { only_integer: true,
                                                      greater_than: 0 },
                                      presence: true, if: :finished?
  validate  :motion_presence

  private

    # Validates the motion depending on debate?
    def motion_presence
      if debate?
        errors.add(:motion, "must be present if a debate was held")
      else
        errors.add(:motion, "cannot be present if a debate was held")
      end
    end
end

2 个答案:

答案 0 :(得分:0)

def motion_presence
  if debate?
    errors.add(:motion, "must be present if a debate was held")
  else
    errors.add(:motion, "cannot be present if a debate was held")
  end
end

这将始终失败,因为您在任何一种情况下都添加了errors

如果您想在多个条件下失败,请尝试在elsif中执行此操作。 else表示EVERYTHING ELSE及其失败。

这样做:

def motion_presence
  if debate?
    errors.add(:motion, "must be present if a debate was held")
  elsif some_condition
    errors.add(:motion, "cannot be present if a debate was held")
  end
end

答案 1 :(得分:0)

这是因为无论debate?是返回true还是false,它都会向运动添加错误,因此它永远不会成功,这会导致不保存课程对象,因为已经为运动字段添加了错误。

我认为你需要添加一个只返回而不添加任何错误的情况。除了为特定情况添加错误