Rescue block未在rails迁移脚本中运行

时间:2015-08-16 19:02:42

标签: ruby-on-rails ruby heroku

我已经生成了以下迁移:

class AddMarketStatusIdToProducts < ActiveRecord::Migration
  def change
    add_column :products, :market_status_id, :integer
  end
end

但是它开始在heroku中引发跟随错误:

20150816131733 AddMarketStatusIdToProducts: migrating =====================
-- add_column(:products, :market_status_id, :integer)
   (1.7ms)  ALTER TABLE "products" ADD "market_status_id" integer
PG::UndefinedTable: ERROR:  relation "products" does not exist
: ALTER TABLE "products" ADD "market_status_id" integer
   (1.0ms)  ROLLBACK
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

错误信息非常清楚,因此我使用了以下迁移脚本:

class AddMarketStatusIdToProducts < ActiveRecord::Migration
  def change
    begin
      add_column :products, :market_status_id, :integer
    rescue PG::UndefinedTable
      create_table :products do |t|
        t.float :price

        t.timestamps null: false
      end
    end
  end
end

但我仍然得到完全相同的错误信息!!我不明白,为什么我的救援代码没有运行?

1 个答案:

答案 0 :(得分:1)

我不确切地知道你的救援模块没有运行的原因但是我认为你的错误实际上就是StandardError: An error has occurred, this and all later migrations canceled:这是一个StandardError,你可以这样处理: rescue StandardError => error。但这只是猜测我不知道这一点。

但正确的做法是:

class AddMarketStatusIdToProducts < ActiveRecord::Migration
  def change
    if table_exists?("products")
      add_column :products, :market_status_id, :integer
    else
      create_table :products do |t|
        t.float :price
        t.integer :market_status_id
        t.timestamps null: false
      end
    end
  end
end

Rails为我们提供了方法table_exists?column_exists?来执行此操作。我从来没有用过这个,但我知道这可以做到。因此,请检查语法,因为我对语法不是100%确定。

希望这有帮助。

相关问题