有两个班级。
头等舱
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
相关联。有效地存储Baby
和Parent
之间的关系。
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.