Foreign keys and mongols

Are foreign keys explicitly required in the relationship between the two models in Mongoid? For instance.

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 

Documents on Mongoid sites do not indicate any field declarations when discussing relationships, so I ask.

+4
source share
2 answers

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

If these conventions are not suitable for your model (for example, if you have two associations with the same class), you can override the foreign key name. eg.

 belongs_to :user, foreign_key: :friend_id 

Again, this is almost the same as ActiveRecord (but without transfer of course).

+7
source

Model region.rb :

 class Region ... field :title has_many :users ... 

user.rb Model:

 class User ... belongs_to :reg, class_name: "Region", foreign_key: :reg_id ... 

Now you can use the region for user as follows user.reg , for example:

 = user.reg.title 
0
source

Source: https://habr.com/ru/post/1489776/


All Articles