Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby + Mongoid: how to make a required field?

I use the githead version of Mongoid (because of Rails 4) and I want to make a field required document with:

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

And I have this error:

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...

What am I doing wrong?

like image 932
Tolsi Avatar asked Oct 26 '13 14:10

Tolsi


1 Answers

You need to use validates_presence_of, so your class would look like this:

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

For further documentation on validation on mongoid, you can use http://mongoid.org/en/mongoid/docs/validation.html.

like image 159
Arthur Neves Avatar answered Oct 19 '22 09:10

Arthur Neves