1
0

More than 3 years have passed since last update.

rails db:rollback後にエラー発生!

Posted at

はじめに

furimaアプリ作成中にカラムを書き忘れて追加しようとした時にエラーが発生しました。

私自身初めてrollbackして追加したのでこのエラーに慣れておらず慌てましたがとても簡単な事でのエラーでした。

エラー内容

下記のDBを作成しました

・itemテーブル(出品商品情報)

・buyerテーブル(購入者情報)

・purchase_history(購入履歴情報)

buyerテーブルには誰が購入したか、何を購入したかを保存した方が良いと考え,purchase_history_idをカラムに追加しました。

README

usersテーブル

Column Type Options
nickname string null: false
email string unique: true
encrypted_password string null: false
family_name string null: false
first_name string null: false
family_name_kana string null: false
first_name_kana string null: false
birth_day date null: false

itemsテーブル

Column Type Options
name string null: false
text text null: false
category_id integer null: false
status_id integer null: false
postage_id integer null: false
region_id integer null: false
shopping_date_id integer null: false
price integer null: false
user references foreign_key: true

buyersテーブル

Column Type Options
post_code string null: false
region_id integer null: false
city string null: false
address string null: false
building_name string
phone_number string null: false
purchase_history_id references foreign_key: true

purchase_history テーブル

Column Type Options
user references foreign_key: true
item references foreign_key: true

マイグレーションを修正する場合は

rails db:rollback

で戻し、マイグレーションに記述し直します。

20210514070000_create_buyers.rb

class CreateBuyers < ActiveRecord::Migration[6.0]
  def change
    create_table :buyers do |t|

      t.string     :post_code,           null: false
      t.integer    :region_id,           null: false
      t.string     :city,                null: false
      t.string     :address,             null: false
      t.string     :building_name
      t.string     :phone_number,        null: false
      t.references :purchase_history, foreign_key: true, null: false
      #追加
      #外部キー制約の記述を行う      

      t.timestamps
    end
  end
end

記述し直し,rails db:migrateを行なったら...

Mysql2::Error: Table 'furima_development.purchase_history_ids' doesn't exist

purchase_history_idsなんて存在しないよ!と言われました。
いやいや笑こちとら既にpurchase_historyテーブル作ってますから!と思い、もう一度
rails db:migrateしても同じエラーでした。

結論

buyerテーブルのマイグレーションを作成した時間がpurchase_historyテーブルを作成した時間より遅かったためでした。

マイグレーションファイルには作成した時間が表示されます

・20210514070000_create_buyers.rb
buyerテーブルは2021年5月14日7:00時作成されました

・2021051408000_create_purchase_histories.rb
purchase_historiesテーブルは2021年5月14日8:00時作成されました

なので名前変更で時間を遅く記述すれば上手くできました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0