2

我正在尝试使用 Ruby on Rails、Mongo 创建一个小型游戏服务器,使用 Mongoid 作为 ORM,并使用 Devise 进行身份验证。我正在尝试修改 db/seeds.rb 以播种多个用户和游戏文档。

您如何在两个 Mongo/Mongoid 关系之间创建种子?

我有用户游戏。用户有_many Games。我找到了为“embeds_many”和“embedded_in”创建种子数据库的示例,但没有为 has/belongs 创建种子数据库的示例。如果这是正确的架构,后续将是(有第三种模型“Turns”将嵌入“游戏”中。

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
4

2 回答 2

1

看起来您正在手动尝试创建关系。field :user_id, type: Integer从游戏模型中删除并 尝试user.games.create!(title: "First Game")

于 2012-08-06T11:53:24.753 回答
0

添加以下代码而不是 belongs_to :games在 Game 类中:并将User 类
embedded_in :user, :inverse_of => :game
替换为has_many :games
embeds_many :games

于 2012-08-06T05:35:44.903 回答