2011-11-30 37 views
1

型號:與MongoMapper驗證協會

class User 
    include MongoMapper::Document 
    many :properties 
    validates_associated :properties 
    ... 
end 

class Property 
    include MongoMapper::Document 
    belongs_to :user 
    many :services 
    validates_associated :services 
    ... 
end 

class Service 
    include MongoMapper::Document 
    belongs_to :property 
    ... 
end 

在控制器:

@property.save #returns false and true as expected 
current_user.save #returns always true why? 

看來,那它不驗證的屬性模型current_user.save方法。 爲什麼? :(

+0

在我的簡短測試中,'validates_associated'只適用於嵌入式關聯。我正在調查,因爲代碼中爲什麼沒有立即清楚。 –

回答

1

在MongoMapper中,分配一個非嵌入的多關聯會自動保存你關聯的記錄,但是如果這些記錄中的任何一個都是無效的,它們將不會保存到數據庫中。該協會MongoMapper進入數據庫,發現什麼都沒有。你指定的無效的記錄消失。

user = User.new(:properties => [Property.new]) 
user.properties # => [] 
user.valid?  # => true 

可以使用build方法來添加對象的關聯,但不保存。

user = User.new 
user.properties.build 
user.properties # => [#<Property _id: BSON::ObjectId('...0e'), user_id: BSON::ObjectId('...0c')>] 
user.valid?  # => false 

我考慮的屁股將節點保存爲MongoMapper的弱點之一。但是,這不是一個簡單的問題。有關挑戰的討論,請參見issue #233 on github