Ruby 在两个mongoid集合之间使用所属对象创建外键

Ruby 在两个mongoid集合之间使用所属对象创建外键,ruby,sinatra,mongoid,Ruby,Sinatra,Mongoid,有两个班 头等舱 class Baby include Mongoid::Document field :first_name, type: String field :surname, type: String field :dob, type: Integer belongs_to :parent, foreign_key: :username validates :parent, :presence => true end 二等舱 class Parent

有两个班

头等舱

class Baby
include Mongoid::Document

  field :first_name, type: String
  field :surname, type: String
  field :dob, type: Integer
  belongs_to :parent, foreign_key: :username
  validates :parent, :presence => true

end
二等舱

class Parent
include Mongoid::Document

  field :username, type: String
  field :first_name, type: String
  field :surname, type: String
  field :email, type: String
  field :password, type: String
  has_many :baby

end
当我创建
Baby
类的一个新实例时,我会传入一个
username
。这应该与
父项
文档中的
用户名
相关。有效地存储
婴儿
父母
之间的关系

Baby.create!(first_name: 'James', surname: 'Barr', dob: '17-09-2012', username: 'foo123')
我每次都会收到这个:

Mongoid::Errors::Validations: 
message:
  Validation of Baby failed.
summary:
  The following errors were found: Parent can't be blank, Parent can't be blank
resolution:
  Try persisting the document with valid data or remove the validations.

它不设置父项的原因是因为它尝试搜索
parent.find('foo123')
,即它假定
username
值与
parent
记录的id匹配。它不设置父项的原因是因为它尝试搜索
parent.find('foo123'))
即,它假定
用户名
值与
父记录的id匹配。