1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

1つのテーブルの複数のカラムに外部キー制約をかける書き方 Rails 5.2

Posted at

備忘録のために書きます。
(こんなケースほとんど無いだろうけど)

1つのテーブルの複数のカラムに外部キー制約をかけようとしてReferences を使おうとしたらRake abotedされました。
References を1つだけに絞ると通ったので、add_reference で強引に追加しました。

エラーがでるパターン

class CreateLikes < ActiveRecord::Migration[5.2]
  def change
    create_table :likes do |t|
      t.references :user, foreign_key: true
      t.references :item, foreign_key: true
      t.timestamps
    end
  end
end

出ないパターン

class CreateLikes < ActiveRecord::Migration[5.2]
  def change
    create_table :likes do |t|
      t.references :user, foreign_key: true
      t.timestamps
    end
    add_reference :likes, :item, foreign_key: true
  end
end

そもそも外部キーを複数つけるのがあまり良く無いのでは無いだろうか・・・

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?