2010-11-15 92 views
1

我有一个Foo类嵌入对象栏。每当创建Foo时,我都希望创建它的Bar。 Bar通过传递来自Foo的变量来启动。我怎样才能做到这一点?MongoDB帮助(关系)

谢谢

+0

你在使用包装库吗?如果是这样,什么? – 2010-11-15 21:29:35

回答

1

使用before_create挂钩来自动创建您的Bar。像

class Foo 
    include Mongo.... 
    attr_reader :new_bar 
    before_create :create_bar 

    def create_bar 
    self.bars << new_bar 
    end 
end 

这样你仍然可以验证酒吧(使用new_bar或任何你想要的)。

MongoMapper和Mongoid都有before_create钩子,所以你应该没问题。

+0

我正在使用mongoid并想使用embed_one:bar。我的控制器(Foo和Bar)应该是什么样子? – timstepp 2010-11-24 20:56:51

+0

@bar = Bar.new(params [:bar]) @ foo.bar = @bar – 2010-11-24 23:46:47

+0

好的。这很好!还有一个问题...... Bar扩展了Array类。我想从Foo模型中的方法调用self.bar.method1(var1,var2 ..)。本质上,我想加载一些默认哈希到Bar timstepp 2010-11-29 01:43:38