Rails数据迁移之谜

时间:2014-07-31 23:24:57

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

我有一个BankAccount模型和一个Card模型。目前,他们都有customer_id和company_id。我试图将这些转换为只是与“所有者”的多态关联。我在模型中添加了适当的关系,然后为所有当前客户和公司编写数据迁移。迁移看起来像这样......

class AddOwnersToCardsAndBanks < ActiveRecord::Migration
  class Card < ActiveRecord::Base; end
  class BankAccount < ActiveRecord::Base; end

  def change
    # Card related changes
    add_column :cards, :owner_id, :integer
    add_column :cards, :owner_type, :string

    # BankAccount related changes
    add_column :bank_accounts, :owner_id, :integer
    add_column :bank_accounts, :owner_type, :string

    Card.all.each do |card|
      if card.try(:customer_id)
        card.update_attribute(:owner_id, card.patient_id)
        card.update_attribute(:owner_type, "Patient")
      end
    end

    BankAccount.all.each do |bank_acount|
      if bank_acount.try(:customer_id)
        bank_acount.update_attribute(:owner_id, bank_acount.customer_id)
        bank_acount.update_attribute(:owner_type, "Patient")
      end
      if bank_acount.try(:company_id)
        bank_acount.update_attribute(:owner_id, bank_acount.company_id)
        bank_acount.update_attribute(:owner_type, "Company")
      end
    end

    remove_column :cards, :customer_id, :integer
    remove_column :bank_accounts, :customer_id, :integer
    remove_column :bank_accounts, :company_id, :integer
  end
end

这在本地工作(看起来似乎如此)。我将其推送到功能服务器,甚至控制台记录了迁移过程中发生的情况。 显示,一切都在迁移中完成了应有的操作(这意味着我在更新后记录了银行帐户,并打印了我所期望的属性)。但是,当我从功能服务器执行rails控制台,并查找已更改的数据时,它似乎只适用于卡,但不适用于银行帐户。

具体来说,owner_id和owner_type实际上从未实际设置在数据库之后的银行账户中。但是当我从迁移中记录这些属性时,它们就像预期的那样存在。这与卡片形成鲜明对比,卡片中的所有内容都设置正确,数据库显示了这一点。我完全糊涂了。

似乎这可能与Heroku或Circle有关,但我不知道。任何关于可能是什么问题的想法都会受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

有时在数据迁移期间,您无法写入刚刚创建的列。尝试将此添加到您的迁移脚本中:

# BankAccount related changes
add_column :bank_accounts, :owner_id, :integer
add_column :bank_accounts, :owner_type, :string

Card.reset_column_information
BankAccount.reset_column_information

Card.all.each do |card|

可在此处找到更多信息: http://apidock.com/rails/ActiveRecord/Base/reset_column_information/class