views:

22

answers:

1

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 can see, we have validated the city and street should be present.

But see following code:

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

And, we use mongo to see the database directly:

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

The address has been inserted. That means validates_presence_of :city, :street in Address is not worked.

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

+1  A: 

try this

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 if you try to save the address then you wont be able to save person Because validates_assocaited :addresses tries to validate address before saving person.
Hope this works

Gagan