在两个mongoid集合之间使用belongs_to创建外键

时间:2017-03-04 12:33:45

标签: 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
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。这应该与username文档中的Parent相关联。有效地存储BabyParent之间的关系。

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.

0 个答案:

没有答案