has_many – the many-to-one relation
The Many-to-One relation is among the most commonly used relations between documents. This is easiest seen in our previous example of authors, and how they are related to their books.
# app/models/author.rb class Author include Mongoid::Document has_many :books end # app/models/book.rb class Book include Mongoid::Document belongs_to :author end
Though it seems very simple at first, let's look a few nuances that are commonly misunderstood.
Notice the model filename is always singular (author.rb
, book.rb
) as is the name of the model—Author
and Book
.
Remember, has_many
is a method that creates an instance method called books
when the Author
class is loaded. Similarly, belongs_to
is a method that creates an instance method called author
when the Book
class is loaded.
The relation names are used to infer the model name. So, using the symbols :books
and :author
, ActiveSupport inflector methods can find out the model names Book
and Author
respectively...