Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign Keys and Mongoid

Are foreign keys explicitly required in relationships between two models in Mongoid? For example.

class User
  include Mongoid::Document
  has_many :posts
end

class Post
  include Mongoid::Document
  belongs_to :user
  # Is this necessary below?
  field :user_id, type: Integer
end

The documents on Mongoid's site don't indicate any declarations of fields when discussing relations which is why I ask.

like image 586
thank_you Avatar asked Jul 04 '13 17:07

thank_you


1 Answers

No, generally separate foreign key field declarations are not needed. Mongoid will implicitly create the user_id field on any documents that need it. It follows the same foreign key naming conventions as ActiveRecord.

If those conventions aren't right for your model (e.g. if you have two associations to the same class) then you can override the foreign key name. e.g.

belongs_to :user, foreign_key: :friend_id

Again this is pretty much the same as ActiveRecord (but without the migrations of course).

like image 139
Steve Avatar answered Oct 19 '22 03:10

Steve