'validates_presence_of' not working in Mongoid?

There are two classes:

class Person include Mongoid::Document field :name embeds_many :addresses end class Address include Mongoid::Document field :city field :street validates_presence_of :city, :street end 

We see that we checked city and street .

But see the following code:

 person = Person.new person.addresses << Address.new person.save #-> true 

And we use mongo to directly view the database:

 $mongo > use the_db > db.people.find() {"_id":"xxxxx", "addresses":[{"_id":"xxxxx"}]} 

Address entered. This means that validates_presence_of :city, :street in Address not working.

Did I miss something? Or is there a bug in Mongoid?

+4
source share
1 answer

try it

 class Person include Mongoid::Document field :name embeds_many :addresses validates_associated :addresses end class Address include Mongoid::Document field :city field :street embedded_in :person validates_presence_of :city, :street end 

Now I think that if you try to save the address, you cannot save the person. Since validates_assocaited: addresses try to verify the address before saving the person.
Hope this works.

+7
source

Source: https://habr.com/ru/post/1315885/


All Articles