I'm trying to create a small game server using Ruby on Rails, Mongo, with Mongoid as the ORM, with Devise for authentication. I'm trying to modify the db/seeds.rb to seed several users and game documents.
How do you create a seed between two Mongo/Mongoid relationships?
I have Users and Games. Users have_many Games. I've found examples of creating a seed database for "embeds_many" and "embedded_in", but not for has / belongs. A follow-up would be if this is the proper architecture (there's a third model "Turns" that will be embedded in the "Game".
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
end
I've tried two ways to make this work and neither create a relationship in the database:
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