xjq233p_1
xjq233p_1

Reputation: 8070

Mongoid with "Foreign Key"

As a veteran of mongodb, I have 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 properly in mongoid:

class User 
  include Mongoid::Document

  has_many :gifts
end

class Gift 
  include Mongoid::Document

  belongs_to :user
end

However, the mapping is not correct. g = Gift.first; g.author is not defined. How do I do the referencing?

Technically, it's:

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

(meaning a user can be the author of many gifts, and a user can be the receiver of many gifts, BUT a gift can have only 1 author and receiver).

Plz help!!!

Upvotes: 4

Views: 3781

Answers (1)

mu is too short
mu is too short

Reputation: 434945

You'll probably have better luck 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 
  ... 
}

And then, add a :foreign_key to Gift:

class Gift 
  include Mongoid::Document

  belongs_to :user, :foreign_key => 'author_id'
end

Upvotes: 6

Related Questions