如何更改连接表上的外键?

时间:2014-09-13 01:56:42

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

我有以下表格。

class Reward ActiveRecord::Base
  has_many :earned_rewards
  has_many :players, :through => :earned_rewards
end

class EarnedReward < ActiveRecord::Base
  belongs_to :reward
  belongs_to :player
end

class Player < ActiveRecord::Base
  has_many :earned_rewards
  has_many :rewards, :through => :earned_rewards
end

我的问题是EarnedReward表上的外键是字符串类型,并且不符合Rails约定。我想将Integer字段(player_id和reward_id)添加到EarnedReward表中以充当新的外键,同时保留旧字段及其值。

我正在使用Rails 4.1.1,我不确定如何完成此任务。

1 个答案:

答案 0 :(得分:0)

如果问题是当前外键具有默认名称,则创建迁移以重命名旧字段,然后创建新字段

class DoBlaBla < ActiveRecord::Migration
  def change
    change_table :earn_rewards do |t|
      t.rename :player_id, :old_player_id
      t.rename :reward_id, :old_reward_id
      t.integer :player_id
      t.integer :reward_id
    end
  end
end

我认为应该这样做,首先在测试数据库上尝试。