0

我是 ruby​​ 和 mongoid 的新手。我需要使用 validates_with 下面是我的代码

class ValidatorClass < ActiveModel::Validator

  def validate(record)

    if record.name == ""

        record.errors.add(:name, "An error occurred")

    end

  end
end

class Person
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  include Mongoid::Timestamps::Updated
  include Mongoid::Versioning
  include ActiveModel::Validations

  field :id, type: Integer
  field :name, type: String
  field :age, type: Integer

   validates_with ValidatorClass, :on => :create

end

但是当我使用以下代码创建模型时:

Person.create(id: 5, name: "", age: 50)

我没有得到抛出的错误。我没有使用 Rails。我只使用 ruby​​ 和 mongodb。有人可以帮我吗?提前致谢。

4

3 回答 3

0

您不必在课堂上包含 ActiveModel::Validations

尝试更改您的验证类以使用以下代码:

class ValidatorClass < ActiveModel::Validator
  def validate(record)
    if record.name.blank?
      record.errors.add(:name, "An error occurred")
    end
  end
end

希望能帮助到你!

于 2012-11-30T16:51:51.427 回答
0

请试试这个:

class ValidatorClass < ActiveModel::Validator

  def validate(record)

        if !record.name.present?
            record.errors.add(:name, "An error occurred")
        end 

  end
end
于 2012-11-30T16:56:27.133 回答
0

从文档中,您可以尝试在 Person 类中添加这一行:

include ActiveModel::Validations

http://api.rubyonrails.org/classes/ActiveModel/Validator.html

于 2012-11-30T16:34:19.693 回答