how to make has_and_belongs_to_many relationship work in mongoid

我与影子孤独终老i 提交于 2019-12-22 07:39:31

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/11096691/how-to-make-has-and-belongs-to-many-relationship-work-in-mongoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!