加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 外键和Mongoid

发布时间:2020-12-17 02:45:42 所属栏目:百科 来源:网络整理
导读:Mongoid中两个模型之间的关系中是否明确要求外键?例如. class User include Mongoid::Document has_many :postsendclass Post include Mongoid::Document belongs_to :user # Is this necessary below? field :user_id,type: Integerend 在讨论关系时,Mongo
Mongoid中两个模型之间的关系中是否明确要求外键?例如.

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

在讨论关系时,Mongoid网站上的文件并未表明任何字段声明,这就是我要求的原因.

解决方法

不,通常不需要单独的外键字段声明. Mongoid将在需要它的任何文档上隐式创建user_id字段.它遵循与ActiveRecord相同的外键命名约定.

如果这些约定不适合您的模型(例如,如果您有两个关联到同一个类),那么您可以覆盖外键名称.例如

belongs_to :user,foreign_key: :friend_id

这与ActiveRecord几乎相同(但当然没有迁移).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读