O'Reilly logo

Learning Mongoid by Gautam Rege

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required