Mongoid with a "Foreign Key"

As a mongodb veteran, I created the following structure:

User: { 
  name: str, 
  email: ... 
}

Gift: { 
  # author and receiver refer to User objects obviously
  author: object_id(...),     
  receiver: object_id(...), 

  name: str 
  ... 
}

And I would like to map this to mongoid correctly:

class User 
  include Mongoid::Document

  has_many :gifts
end

class Gift 
  include Mongoid::Document

  belongs_to :user
end

However, the display is incorrect. g = Gift.first; g.author is undefined. How do I make a link?

Technically, this is:

User <--- 1: N via author---> Gift <--- N:1 via receiver---> User

(this means that the user can be the author of many gifts, and the user can be the recipient of many gifts, BUT a gift can only have 1 author and recipient).

Help Plz !!!

+3
source share
1 answer

You'll probably be lucky with Rails if Gift looks like this:

Gift: { 
  # author and receiver refer to User objects obviously
  author_id: object_id(...),     
  receiver_id: object_id(...), 

  name: str 
  ... 
}

Then add :foreign_keyas a gift:

class Gift 
  include Mongoid::Document

  belongs_to :user, :foreign_key => 'author_id'
end
+5
source

All Articles