1

MongoMapper でプラグインを使用して、associationsクラス間に多対 1 の関連付けを作成する方法はありますか? これが私の試みです。

class Foo
    include MongoMapper::Document
end

class Bar
    include MongoMapper::Document

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

メソッドはone1 対 1 の関連付けを前提としており、単一のBarインスタンスのみが特定のFoo.

foo = Foo.new

bar1 = Bar.new
bar1.foo = foo

bar2 = Bar.new
bar2.foo = foo

bar1.foo #=> nil :(

Fooクラスに 1 対多の関連付けを作成したくありませんBar

単純に a を保存することfoo_idもできますが、このBar#foo方法は非常に便利です。

4

1 に答える 1

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
于 2014-02-12T19:52:26.900 に答える