how to make has_and_belongs_to_many relationship work in mongoid

mongoid, ruby-on-rails-3

Solution

I had exactly the same issue ;) Make sure you're using mongodb version > 2.0.0, for more details see: http://mongoid.org/en/mongoid/docs/installation.html#installation

Problem

i have the following code in the rails company model: ``` class Company include Mongoid::Document include Mongoid::Timestamps field :name, type: String ... has_and_belongs_to_many :users end ``` User model: ``` class User include Mongoid::Document include Mongoid::Timestamps include ActiveModel::SecurePassword field :email, type: String ... has_and_belongs_to_many :companies end ``` There is a company record in the database, and a user record and they are associated. For some reason, the following code does NOT work: ``` c = Company.first c.users # returns empty array ``` similarly, the followign code does not work: ``` u = User.first u.companies ``` But the following code DOES work: ``` c = Company.first user = User.find c.user_ids.first ``` and the following code also works: ``` u = User.first company = Company.find u.company_ids.first ``` so if i try to access users from the company.users, it does not work, but the user_ids array does have a list of user ids, and when i try to access the users from this list, it works. How can i fix this issue? i am using rails 3.2.5 and mongoid 3.0.0.rc

Original source