如何使用Mongoid在MongoDB中自动创建相关记录?

时间:2013-04-24 05:40:34

标签: ruby mongoid associations autocreate

我仍然专注于MongoDBMongoid

假设我有一个User,每个User只有一个Thingamajig。当我创建User时 我希望系统自动为Thingamajig创建一个空白User

每个Thingamajig都有一个whatsit字段,如果它有值,则必须是唯一的,但在创建时不允许有值。

所以我定义了以下类。

class Thingamajig
  include Mongoid::Document
  field :whatsit, type: String
  index({whatsit: 1}, {unique: true, name: 'whatsit_index'})
end

class User
  include Mongoid::Document
  field :name, type: String
  index({name: 1}, {unique: true, name: 'user_name_index'})
  embeds_one :thingamajig, dependent: :nullify, autobuild: true
end

然而,当我

时,我发现了什么
User.create!(name: 'some name')

User.find(name: 'some name').thingamajig是零。

问题:

  1. 如何确保每位用户获得相关的Thingamajig?和
  2. 如何指定name的{​​{1}}字段是否必需?
  3. 仅供参考我使用User而不是Sintara(如果这对任何人都很重要)。

1 个答案:

答案 0 :(得分:2)

1 - autobuild: true选项通常应该完成。我认为问题在于你忘了将关系的另一面添加到Thingamajig模型中:

class Thingamajig
  include Mongoid::Document
  embedded_in :user
  ...
end

2 - 要指定必填字段,请使用validations

class User
  include Mongoid::Document
  field :name, type: String
  validates_presence_of :name
  ...
end

Mongoid使用ActiveModel validations

相关问题