2011-11-30 67 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