mongoid embeds_one 构建指南

mongoid embeds_one build howto

感谢您的宝贵时间!

代码简单(没有rails使用mongoid):

require 'mongoid' # version 6.0.2

Mongoid.load!('mongoid.yml', :development)

class Office
  include Mongoid::Document

  embeds_one :owner
  embeds_many :addresses
end

class Owner
  include Mongoid::Document
end

class Address
  include Mongoid::Document
end

我可以按如下方式成功调用 office.addresses.build

office = Office.new
office.addresses.build
office.save

但是当我调用 office.owner.build 时,错误弹出说

embed_one.rb:23:in `<main>': undefined method `build' for nil:NilClass (NoMethodError)

应该是这样的吧?哪里错了。

puts office.owner.class # NilClass

一觉醒来后...

我使用 puts office.methods 列出了 office 可以调用的所有方法。

# Here's all the methods has *owner* in it
owner=
owner?
has_owner?
build_owner
create_owner
owner

office.build_owner 正是我要找的!