【问题标题】:Many-to-one associations in MongoMapperMongoMapper 中的多对一关联
【发布时间】:2013-02-19 08:26:17
【问题描述】:

有没有办法在 MongoMapper 中使用 associations 插件在类之间创建多对一关联?这是我的尝试。

class Foo
    include MongoMapper::Document
end

class Bar
    include MongoMapper::Document

    key :foo_id, ObjectId
    one :foo, :in => :foo_id
end

此实现不起作用,因为one 方法假定一对一关联并且只允许单个Bar 实例包含特定Foo 的ID。

foo = Foo.new

bar1 = Bar.new
bar1.foo = foo

bar2 = Bar.new
bar2.foo = foo

bar1.foo #=> nil :(

我不想在 Foo 类中创建一对多关联,因为它不应该包含 Bar 的知识。

简单地存储一个foo_id 是可能的,但是Bar#foo 方法真的很有用。

【问题讨论】:

    标签: ruby mongodb mongomapper


    【解决方案1】:

    我一直在寻找有关此问题的答案,但找不到任何确定的答案。我最终在我的模型中添加了一个方法来运行手动连接。以下是您的示例中的代码:

    class Foo
        include MongoMapper::Document
    end
    
    class Bar
        include MongoMapper::Document
    
        key :foo_id, ObjectId
    
        def foo
            Foo.find(foo_id)
        end
    
        def foo=(a_foo)
            foo_id = a_foo.id
        end
    
        def serializable_hash(options = {})
            hash = super(options)
            hash.merge({'foo' => foo.serializable_hash})
        end
    
    end
    
    foo = Foo.new
    
    bar1 = Bar.new
    bar1.foo = foo
    
    bar2 = Bar.new
    bar2.foo = foo
    
    bar1.foo # Should return expected value
    

    【讨论】:

    • 我不再使用 MongoDB,但这个答案很简单,虽然不是超级优雅,但它可能对某人有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多