【问题标题】:Using validates_with with ruby and mongoid将 validates_with 与 ruby​​ 和 mongoid 一起使用
【发布时间】:2012-11-18 21:43:01
【问题描述】:

我是 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。有人可以帮我吗?提前致谢。

【问题讨论】:

    标签: ruby validation activerecord exception-handling mongoid


    【解决方案1】:

    请试试这个:

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

    【讨论】:

    • 正如我已经说过的。它进入状态。但我没有收到错误消息“发生错误”。
    【解决方案2】:

    你不必在你的类中包含 ActiveModel::Validations

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

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

    希望对你有帮助!

    【讨论】:

    • 进入状态。但我没有收到错误消息“发生错误”。
    • 尝试检查如下错误:a = Person.new -> a.save -> a.errors[:name]。你会看到你的错误。如果你调用model.create!它将引发 Mongoid::Errors::Validations 异常。调用Person.new.create时模型没有持久化,但是可以通过调用Person.create.valid来检查它是否无效?
    • 是的。这就说得通了。无论如何我可以看到并处理 Mongoid (Mongoid::Errors::Validations) 引发的异常吗?谢谢。
    • 是的。如果你愿意,你可以使用默认的 ruby​​ 异常处理来处理异常:tutorialspoint.com/ruby-on-rails-2.1/…。希望对您有所帮助!
    【解决方案3】:

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

    include ActiveModel::Validations
    

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

    【讨论】:

      猜你喜欢
      • 2013-02-19
      • 2012-10-28
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多