将数据传输到连接表:Rails 4

时间:2018-03-14 20:42:36

标签: ruby-on-rails ruby-on-rails-4 activerecord migration

我有一个导轨模型Game和另一个模型Player。目前,分配给游戏的玩家的数据存储在games表中的(玩家ID)数组中。

我正在尝试创建一个连接表来连接游戏,我创建了一个HABTM联接表games_players,然后我尝试运行迁移来传输数据在运行另一次迁移之前,从players表中删除games数组。

我传输数据的代码如下:

games = Game.all
games.each do |g|
  game = g
  games.players.each do |p|
    game.players << p
  end
end

但它并没有在连接表中保存数据,而是继续删除games表中的数组列。如何在删除属性之前将所有这些数据传输到新的连接表?

添加了协会以澄清:

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

1 个答案:

答案 0 :(得分:1)

假设Game#player_ids返回现有Player id的数组 整数,你应该能够做到:

Game.find_each do |game|
  game.player_ids.each do |player_id|
    game.games_players.create!(player_id: player_id)
  end
end

但是此代码暗示您尚未在has_many :players, through: :games_players模型上定义关系Game,因为它使用player_ids作为列games.player_ids的属性读取器