ruby-on-railsmongoidmoped

Storing a collection of mongoid documents with one operation


When using Moped gem, I can store an array of hashes with:

users = [{username: "ben", password: "123456", type: "admin" }, {username: "joe", password: "abcd1234" }]
Mongoid::Sessions.default["collection"].insert(users)

With mongoid documents it would look like:

class User
  field :username, type: String
  field :password, type: String
end

users.each { |user_hash| User.create(user_hash) }

Which means an insertion operation for each. Do you know a way to keep the single operation method? Maybe something like a transaction in ActiveRecord?


Solution

  • You can convert Documents back to Hashes and insert them with single call to #create:

    User.create(users.map(&:attributes))