0
我正在通過this Stackoverflow answer閱讀關於如何在一個查詢中插入Mongoid中的多個文檔。從我讀的答案:用Mongoid批量插入多個記錄?
batch = [{:name => "mongodb"}, {:name => "mongoid"}]
Article.collection.insert(batch)
我需要一個例子來了解它是如何工作的。假設我們有文章分類:
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的是一樣的嗎?
感謝您的回答。但是應該在哪裏放入index({remote_id:1},{unique:true})。它是否在模型中? – ChristofferJoergensen
是的,請參閱文檔以獲取更多詳細信息http://mongoid.org/en/mongoid/docs/indexing.html – Zakwan
任何想法如何在服務器上創建索引。在本地,您可以簡單地從終端位置的終端創建索引。但在服務器上,似乎我無法從'〜/ applications/myapp/current'中執行。 – ChristofferJoergensen