【问题标题】:How do I autocreate associated records in MongoDB using Mongoid?如何使用 Mongoid 在 MongoDB 中自动创建关联记录?
【发布时间】:2013-04-24 05:40:33
【问题描述】:

尤其是MongoDBMongoid,我仍然在思考。

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

每个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 是 nil。

问题:

  1. 如何确保每个用户都获得关联的 Thingamajig?和
  2. 如何指定Username 字段是必需的?

仅供参考,我使用的是 Sintara 而不是 Rails(如果这对任何人都很重要的话)。

【问题讨论】:

    标签: ruby mongoid associations autocreate


    【解决方案1】:

    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

    【讨论】:

    • 我假设也有一个等效的validates_uniqueness_of
    • 是的。 ActiveModel/Mongoid 为您提供大量验证。 (请参阅我添加的链接。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    相关资源
    最近更新 更多