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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With