Ruby on Rails Mongoid Classic Associations

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


Mongoid allows the classic ActiveRecord associations:

  • One-to-one: has_one / belongs_to
  • One-to-many: has_many / belongs_to
  • Many-to-many: has_and_belongs_to_many

To add an association (lets say the User has_many posts), you can add this to your User model file:

has_many :posts

and this to your Post model file:

belongs_to :user

This will add a user_id field in your Post model, add a user method to your Post class, and add a posts method to your User class.

Got any Ruby on Rails Question?