为什么验证不适用于embeds_one
?
class Foo
include Mongoid::Document
embeds_one :bar, :cascade_callbacks => true
end
class Bar
include Mongoid::Document
embedded_in :foo
field :test, :type => String
field :year, :type => Integer, :default => Time.now.utc.year
field :month, :type => Integer, :default => Time.now.utc.month
field :day, :type => Integer, :default => Time.now.utc.day
# validates :year, :uniqueness => true, :presence => true, :scope => [:month, :day]
# validates :day, :uniqueness => { :scope => [:month,:year] }
validates_uniqueness_of :year, :scope => :day
end
Foo.create(:bar => { :test => 'asdf' }) # created document
Foo.create(:bar => { :test => 'asdf' }) # created document, no validation thrown!
为什么要多次创建Foo?
答案 0 :(得分:1)
关于validates_uniqueness_of
,Mongoid's document说:
验证属性是否唯一。请注意,对于嵌入式文档,这只会检查该字段在父文档的上下文中是唯一的,而不是整个数据库。
在您的情况下,示例中会创建两个不同的文档。因此,Mongoid中的行为是正确的。