【问题标题】:Transfer data to join table: Rails 4将数据传输到连接表:Rails 4
【发布时间】:2018-03-14 20:42:36
【问题描述】:

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

我正在尝试创建一个连接表来连接游戏,并创建了一个HABTM 连接表games_players,然后我尝试运行迁移以传输数据,然后再运行另一个迁移以删除@来自games 表的 987654326@ 数组。

我的数据传输代码如下:

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

【问题讨论】:

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


    【解决方案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
    

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

    【讨论】:

    • 好的,所以当我将模型名称更改为 GamesPlayer 时,这非常有效,因为我猜想,rails 将模型复数化的方式。我选择这个作为正确答案,因为它回答了原始问题,但我不确定我命名模型的方式是否是最好的方式
    猜你喜欢
    • 2014-05-26
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2015-01-05
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    相关资源
    最近更新 更多