Question

Is there a way to use the associations plugin in MongoMapper to create a many-to-one association between classes? Here is my attempt.

class Foo
    include MongoMapper::Document
end

class Bar
    include MongoMapper::Document

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

This implementation does not work because the one method assumes a one-to-one association and allows only a single Bar instance to contain the id of a specific Foo.

foo = Foo.new

bar1 = Bar.new
bar1.foo = foo

bar2 = Bar.new
bar2.foo = foo

bar1.foo #=> nil :(

I would not like to create a one-to-many association in the Foo class because it should hold no knowledge of Bar.

Simply storing a foo_id is possible, but the Bar#foo method is really useful.

Was it helpful?

Solution

I've been searching for an answer on this issue, but couldn't find anything definitive. I ended up adding a method to my model to run a manual join. Here is what the code would look like in your example:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top