我正在尝试使用Ruby on Rails,Mongo创建一个小型游戏服务器,使用Mongoid作为ORM,使用Devise进行身份验证。我正在尝试修改db / seeds.rb以播种多个用户和游戏文档。
如何在两个Mongo / Mongoid关系之间创建种子?
我有用户和游戏。用户 have_many 游戏。我找到了为“embeds_many”和“embedded_in”创建种子数据库的示例,但没有为has / belongs创建。如果这是适当的架构,那将是一个后续行动(第三个模型“转向”将嵌入“游戏”中。
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
答案 0 :(得分:1)
您似乎在手动尝试创建关系。
从游戏模型中删除field :user_id, type: Integer
并尝试
user.games.create!(title: "First Game")
答案 1 :(得分:0)
在游戏课程中添加以下代码,而不是 belongs_to :games
:embedded_in :user, :inverse_of => :game
用“has_many :games
替换用户类的embeds_many :games
}