开发者

Rails3/Mongoid - Basic db:seed with embedded documents

开发者 https://www.devze.com 2023-04-12 07:26 出处:网络
I\'m using MongoID with rails 3.1. and I would like to seed my database (both in dev and production). I have a Pages model with Feeds embedded. What\'s the best way for me to seed the embedded feeds f

I'm using MongoID with rails 3.1. and I would like to seed my database (both in dev and production). I have a Pages model with Feeds embedded. What's the best way for me to seed the embedded feeds for each page? I can easily seed all of the page data just not the embedded feeds. Please note that I'm looking to actual have real unique data for these pages/feeds not just arbitrary test data. thanks!

page.rb (model)

...
embeds_many :feeds

feed.rb (model)

class Feed
include Mongoid::Document
field :source, :type => String
field :user, :type => String

embedded_in :page, :inverse_of => :feeds end

db/seeds.rb

Page.create(title: "Page 1", userID: "EMAIL@gmail.com", presentation: 'cards', customURL: 'testing1')
Page.create(title: "Page 2", userID: "EMAIL@gmail.com", presentation: 'cards', customURL: 'tes开发者_JAVA技巧ting2')
Page.create(title: "Page 3", userID: "EMAIL@gmail.com", presentation: 'cards', customURL: 'testing3')
Page.create(title: "Page 4", userID: "EMAIL@gmail.com", presentation: 'cards', customURL: 'testing4')
Page.create(title: "Page 5", userID: "EMAIL@gmail.com", presentation: 'cards', customURL: 'testing5')

How best can I embed some feed data in each page? Thanks much.


Page.create(title: "blah", feeds: [
  Feed.new(source: "blahblah", user: "me!"),
  Feed.new(....),
  Feed.new(.....),
])

Is how I do it in my db:seed, I even have a few that are multiple documents deep.


You can do something like this:

(1..5).each do |i|
  page = Page.create(title: "Page #{i}", userID: "EMAIL@gmail.com", presentation: 'cards', customURL: "testing#{i}")

  3.times { Feed.create(page: page) }
end
0

精彩评论

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

关注公众号