mongoid embeds_one build howto

时间:2016-12-05 08:50:14

标签: ruby mongoid

谢谢你的时间!

代码很简单(没有导轨使用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

1 个答案:

答案 0 :(得分:1)

从睡梦中恢复过来......

我使用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正是我正在寻找的!