Rails Rails 5 validates on: :update 验证问题

harryyoung · 2016年09月27日 · 最后由 harryyoung 回复于 2016年09月28日 · 1739 次阅读

我需要在更新的时候验证一个字段存在,而在创建的时候不验证。

model 中的代码:

class Ent < ApplicationRecord
  validates :name, presence: true, on: :update
end

测试代码:

require 'test_helper'

class EntTest < ActiveSupport::TestCase

  test "ent attributes must not be empty when creating" do
    ent = Ent.create
    assert ent.invalid?
    assert ent.errors[:name].any?
  end

  test "ent attributes must not be empty when updating" do
    ent = Ent.first
    ent.update(name: '')
    assert ent.invalid?
    assert ent.errors[:name].any?
  end

end

然而以上两个测试竟然都通过了,按道理应该是前面那个应该失败的。

请问我哪里写错了吗?谢谢。(把验证那行注释掉,两个测试都正常失败)

Ent.create 已经创建了数据。 那么再执行 ent.invalid? 或者 ent.valid? 它会认为你要 update,name 为空,则报错。 ent = Ent.create 改成 ent = Ent.new 再看看

#1 楼 @yakjuly 按你的方法 OK 了,谢谢。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号