开发者

'validates_presence_of' doesn't work well in Mongoid?

开发者 https://www.devze.com 2023-01-07 19:16 出处:网络
There are two classes: class Person include Mongoid::Document field :name embeds_many :addresses end class Address

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":开发者_StackOverflow[{"_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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消