LoginSignup
6
4

More than 3 years have passed since last update.

ridgepoleで外部キーをつける

Posted at

はじめに

データベース作成にridgepoleを使ってみました。
マイグレーションファイルが増えず、カラムの追加や削除も簡単なのがいいですね。
ただ、外部キーの作成時に迷ったことがあったので残しておきます。

外部キーのつけかた

まずは、GemのGitHubを見てみます。

create_table "parent", force: :cascade do |t|
end

create_table "child", id: false, force: :cascade do |t|
  t.integer "id"
  t.integer "parent_id"
end

add_index "child", ["parent_id"], name: "par_ind", using: :btree

add_foreign_key "child", "parent", name: "child_ibfk_1"

MySQLではインデックスを勝手に貼ってくれるみたいなので、add_indexは書かずに、add_foreign_keyだけ書いてみるというやり方を取ってみました。
以下は、私のソースコードです。

Schemafile
create_table "users", force: :cascade do |t|
  t.string   "email"
  t.string   "password"
end

create_table "tasks", force: :cascade do |t|
  t.belongs_to  "user", null: false, foreign_key: true
  t.string   "title"
end

add_foreign_key "tasks", "users", name: "task_ibfk_1"

ポイント

t.belongs_to "model", null: false, foreign_key: trueをつける

これをつけずにt.integer "user_id"と書いてしまうと、次のようなエラーが出ます。
bigintとintで型が違うから合わせろということみたいなのですが、デフォルトのbigintでidをつけたほうがいいと思い、上のような書き方にしました。

Column `user_id` on table `tasks` does not match column `id` on `users`, which has type `bigint(20)`. To resolve this issue, change the type of the `user_id` column on `users` to be :bigint. (For example `t.bigint :user_id`).

この形にするまで結構時間がかかってしまった、、、

6
4
1

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
6
4