Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make has_and_belongs_to_many relationship work in mongoid

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

like image 782
umar Avatar asked Nov 03 '22 21:11

umar


1 Answers

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

like image 54
luacassus Avatar answered Nov 14 '22 13:11

luacassus