Skip to content

Instantly share code, notes, and snippets.

@dmitryame
Created April 21, 2011 13:21
Show Gist options
  • Save dmitryame/934457 to your computer and use it in GitHub Desktop.
Save dmitryame/934457 to your computer and use it in GitHub Desktop.
model embedded collection of object_ids with mongoid
If you set has_and_belongs_to_many on one side only, then you need to
set :inverse_of to nil. For example:
class A
include Mongoid::Document
has_and_belongs_to_many :bs, :inverse_of => nil
end
class B
include Mongoid::Document
end
That should work with no trouble. Since you do not have the
relationship set up on the B side, you must do everything via A's
accessors.
The has_and_belongs_to_many macro will try to set up relationship on
both sides. Consider the following:
a = A.new
b = B.new
a.bs << b
After adding b to a's collection of B's, Mongoid will try to access
b's collection of A's and add a to that collection. The name of the
relationship on the other side is declared by :inverse_of. By default,
Mongoid will expect b to have a collection named as. Since B does not
have this relationship, we must tell Mongoid that there is no inverse,
ie. :inverse_of => nil.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment