gpt4 book ai didi

ruby-on-rails - 您如何在 Ruby on Rails 中为 Mongoid 建立关系?

转载 作者:可可西里 更新时间:2023-11-01 10:44:37 27 4
gpt4 key购买 nike

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

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

我有用户游戏。用户有_很多游戏。我找到了为“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

最佳答案

看起来您正在手动尝试创建关系。从游戏模型中移除 field :user_id, type: Integer并尝试user.games.create!(标题:“第一场比赛”)

关于ruby-on-rails - 您如何在 Ruby on Rails 中为 Mongoid 建立关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11821068/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com