Ruby + Mongoid:如何制作必填字段?

时间:2013-10-26 14:00:34

标签: ruby-on-rails ruby mongoid ruby-on-rails-4

我使用Mongoid的githead版本(因为Rails 4),我想用以下字段创建一个字段所需的文档:

class MyClass
  include Mongoid::Document
  field :name,              type: String, required: true

我有这个错误:

Problem: Invalid option :required provided for field :name. Summary: Mongoid requires that you only provide valid options on each field definition in order to prevent un...

我做错了什么?

1 个答案:

答案 0 :(得分:9)

您需要使用validates_presence_of,因此您的课程将如下所示:

class MyClass
  include Mongoid::Document
  field :name, type: String
  validates_presence_of :name
end

有关mongoid验证的进一步文档,您可以使用http://mongoid.org/en/mongoid/docs/validation.html