has_and_belongs_to_many – the many-to-many relation
Let's assume that books belong to many categories and categories have many books. This is the Many-to-Many relationship method. A typical class would look like the following:
class Book include Mongoid::Document has_and_belongs_to_many :categories end class Category include Mongoid::Document has_and_belongs_to_many :books end
It takes all the standard options such as :autosave
, :dependent
, :foreign_key
, :index
, :primary_key
, and :order
. It also supports the :before_add
, :after_add
, :before_remove
, and :after_remove
relation callbacks.
Note
A Many-to-Many relation cannot be a part of a polymorphic relation. This is because a polymorphic relation expects an explicit parent-child relationship and Many-to-Many relations are peer relations.
:inverse_of
Among all the other options, the inverse_of
relation is a very interesting one. As with Many-to-Many relations, the document IDs are stored as arrays on both sides of the association. So...