How to make has_and_belongs_to_many work in mongoid

I have the following code in a 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

The database has a company record and a user record, and they are related. For some reason, the following code does NOT work:

c = Company.first
c.users # returns empty array

Similarly, the subtitle code does not work:

u = User.first
u.companies

But the following code works:

c = Company.first
user = User.find c.user_ids.first

and the following code works:

u = User.first
company = Company.find u.company_ids.first

therefore, if I try to access users from company.users, it does not work, but the user_ids array has a list of user identifiers, and when I try to access users from this list, it works. How can I fix this problem?

I use rails 3.2.5 and mongoid 3.0.0.rc

+5
source share

All Articles