使用带有ruby和mongoid的validates_with

时间:2012-11-30 16:27:02

标签: ruby validation activerecord exception-handling mongoid

我是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。我正在使用红宝石和mongodb。有人可以帮助我吗?提前谢谢。

3 个答案:

答案 0 :(得分:0)

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

include ActiveModel::Validations

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

答案 1 :(得分:0)

您不必在课程中包含ActiveModel :: Validations

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

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

希望它有所帮助!

答案 2 :(得分:0)

请试试这个:

class ValidatorClass < ActiveModel::Validator

  def validate(record)

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

  end
end