我正在阅读有关如何在一个查询中在 Mongoid 中插入多个文档的 Stackoverflow答案。从我读到的答案:
batch = [{:name => "mongodb"}, {:name => "mongoid"}]
Article.collection.insert(batch)
我需要一个例子来理解它是如何工作的。假设我们有 Article 类:
class Article
include Mongoid::Document
include Mongoid::Timestamps
field :subject, type: String
field :body, type: String
field :remote_id, type: String
validates_uniqueness_of :remote_id
belongs_to :news_paper, :inverse_of => :articles
end
例如,我创建了一系列文章:
[ {subject: "Mongoid rocks", body: "It really does", remote_id: "1234", news_paper_id: "abc"},
{subject: "Ruby rocks", body: "It really does", remote_id: "1234", news_paper_id: "abc"},
{subject: "Rails rocks", body: "It really does", remote_id: "5678", news_paper_id: "abc"} ]
如何创建它们,同时确保验证捕获到我有 2 个相同的 remote_id?