开发者

Seed embedded documents to MongoDB using Rails rake db:seed

开发者 https://www.devze.com 2023-04-12 11:01 出处:网络
How should db.seeds be structured in order to provide data for MongoDB, especially when containing embedded documents?

How should db.seeds be structured in order to provide data for MongoDB, especially when containing embedded documents?

I ran into the following error when trying to seed a supposedly wrongly structured db.seeds file :

Cannot serialize an object of class ClassName into BS开发者_运维技巧ON.


Start by creating a 'new' nested object like address, with attribute street and city, and setting it equal to a variable. Then create the parent object, in this case user with an attribute address, and assign the variable you created above to it. Since it is a nested object, you need to wrap your variable in an array []. Doing it this way will make it easy to read especially if you have a lot of nested objects. When referencing the nested object make sure to exclude any spaces after the colon or you will get an error.

a = Address.new(street: 'Any_Street', city: 'Any_City')
User.create(address:[a])

This will seed mongoDB with an address object which is nested in the user object.


Parent.create(title: 'foo', children: [
  Child.create(title: 'bar', date: Time.utc(2011,10,13)),
  Child.create(...),
  Child.create(...)
])
0

精彩评论

暂无评论...
验证码 换一张
取 消