我试图创建一个使用Ruby on Rails的,蒙戈,与Mongoid作为ORM,与设计用于验证的小游戏服务器。 我试图修改DB / seeds.rb种子多个用户和游戏文件。
你如何创建两个蒙戈/ Mongoid关系之间的种子?
我有用户和游戏 。 用户have_many游戏。 我发现创造“embeds_many”和“embedded_in”种子库的例子,但不具有/所属。 后续是,如果这是正确的架构(还有第三种模式“打开”,将被嵌入在“游戏”。
class Game
include Mongoid::Document
belongs_to :user
embeds_many :turns
field :title, type: String
field :user_id, type: Integer
field :current_player, type: Integer
end
class User
include Mongoid::Document
has_many :games
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
## Database authenticatable
field :email, :type => String, :default => ""
field :encrypted_password, :type => String, :default => ""
validates_presence_of :email
validates_presence_of :encrypted_password
field :name
validates_presence_of :name
validates_uniqueness_of :name, :email, :case_sensitive => false
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
...
... bunch of fields to support devise gem
结束
我已经尝试了两种方法,使这项工作,并没有在数据库中创建一个关系:
puts 'EMPTY THE MONGODB DATABASE'
::Mongoid::Sessions.default.drop
puts 'SETTING UP DEFAULT USER LOGIN'
user = User.create! :name => 'First User', :email => 'user@example.com', :password => 'please', :password_confirmation => 'please'
puts 'New user created: ' << user.name
game = Game.create! :title => 'First Game', :user_id => user._id, :current_player => user._id
puts 'New game created: ' << game.title
user.games.push(game)
user.save
game2 = Game.create(:title => 'Foo Game', users: [
User.create(:name => 'd1', :email => 'd1@example.com', :password => 'd', :password_confirmation => 'd'),
User.create(:name => 'd2', :email => 'd2@example.com', :password => 'd', :password_confirmation => 'd'),
User.create(:name => 'd3', :email => 'd3@example.com', :password => 'd', :password_confirmation => 'd')
])
puts 'Second game created: ' << game2.title