传输数据加入 table: Rails 4
Transfer data to join table: Rails 4
我有一个 rails 模型 Game
和另一个模型 Player
。目前,分配给游戏的玩家数据存储在 games
table.
中的一个数组(玩家 ID)中
我正在尝试创建一个连接 table 来连接游戏,我创建了一个 HABTM
连接 table games_players
然后我正在尝试 运行 迁移以在 运行 进行另一迁移以从 games
table.
中删除 players
数组之前传输数据
我传输数据的代码如下:
games = Game.all
games.each do |g|
game = g
games.players.each do |p|
game.players << p
end
end
但它根本不保存连接 table 中的数据,而是继续删除 games
table 中的数组列。如何在删除属性之前将所有这些数据传输到新连接 table?
添加关联以进行说明:
class GamesPlayers < ActiveRecord::Base
belongs_to :game, inverse_of: :games_players
belongs_to :player, inverse_of: :games_players
end
class Game < ActiveRecord::Base
has_many :games_players, inverse_of: :game
has_many :players, through: :game_players
end
class Player < ActiveRecord::Base
has_many :games_players, inverse_of: :player
has_many :games, through: :games_players
end
假设 Game#player_ids
returns 现有数组 Player
id
整数,你应该能够做到:
Game.find_each do |game|
game.player_ids.each do |player_id|
game.games_players.create!(player_id: player_id)
end
end
但此代码暗示您尚未在 Game
模型上定义关系 has_many :players, through: :games_players
,因为它使用 player_ids
作为列 reader 的属性 games.player_ids
我有一个 rails 模型 Game
和另一个模型 Player
。目前,分配给游戏的玩家数据存储在 games
table.
我正在尝试创建一个连接 table 来连接游戏,我创建了一个 HABTM
连接 table games_players
然后我正在尝试 运行 迁移以在 运行 进行另一迁移以从 games
table.
players
数组之前传输数据
我传输数据的代码如下:
games = Game.all
games.each do |g|
game = g
games.players.each do |p|
game.players << p
end
end
但它根本不保存连接 table 中的数据,而是继续删除 games
table 中的数组列。如何在删除属性之前将所有这些数据传输到新连接 table?
添加关联以进行说明:
class GamesPlayers < ActiveRecord::Base
belongs_to :game, inverse_of: :games_players
belongs_to :player, inverse_of: :games_players
end
class Game < ActiveRecord::Base
has_many :games_players, inverse_of: :game
has_many :players, through: :game_players
end
class Player < ActiveRecord::Base
has_many :games_players, inverse_of: :player
has_many :games, through: :games_players
end
假设 Game#player_ids
returns 现有数组 Player
id
整数,你应该能够做到:
Game.find_each do |game|
game.player_ids.each do |player_id|
game.games_players.create!(player_id: player_id)
end
end
但此代码暗示您尚未在 Game
模型上定义关系 has_many :players, through: :games_players
,因为它使用 player_ids
作为列 reader 的属性 games.player_ids