Reputation: 11107
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.
Upvotes: 5
Views: 4112
Reputation: 13056
Model region.rb
:
class Region
...
field :title
has_many :users
...
Model user.rb
:
class User
...
belongs_to :reg, class_name: "Region", foreign_key: :reg_id
...
You can now use region
for user
as follows user.reg
, for example:
= user.reg.title
Upvotes: 0
Reputation: 15736
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).
Upvotes: 7