2013-05-17 44 views
0

爲什麼不驗證使用embeds_one爲什麼不使用`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被多次創建?

回答

1

關於validates_uniqueness_ofMongoid's document說:

驗證的屬性是唯一的。請注意,對於嵌入式文檔,這隻會檢查該字段在父文檔的上下文中是唯一的,而不是整個數據庫。

就你而言,在這個例子中創建了兩個不同的文檔。因此,Mongoid中的行爲是正確的。