我已在批量插入中阅读了答案,例如batch insert mongoid
我有两个系列:
class User
include UpdateUserOrCreate
include Mongoid::Document
include Mongoid::Timestamps
has_many :messages, class_name: "Api::V1::Message", autosave: true, validate: false
has_many :message_export_requests, class_name: "Api::V1::MessageExportRequest", autosave: true, validate: false
end
class Message
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user, class_name: "Api::V1::User", autosave: true, foreign_key: :user_id
end
我有一个文档数组:
batch = [{name: "dsfdf" },{name: "dfsdfh"}]
我正在尝试:
user.messages.collection.insert(batch)
但结果是Message文档以user_id = nil。
保存如何通过确保外键设置的关系批量保存数组中的文档?
答案 0 :(得分:0)
试试这个:
attr_accessor :id, :username
同样在您的情况下,您需要将其添加到消息模型:
user.messages.create(batch)
=== UPDATE === 也许这可能有用:
field :name
答案 1 :(得分:0)
collection
返回驱动程序的收集对象。驾驶员不了解Mongoid模型。您需要显式设置关联链接:
batch = [{name: "dsfdf", user_id: user.id },{name: "dfsdfh", user_id: user.id}]
user.messages.collection.insert(batch)