LoginSignup
0
0

More than 3 years have passed since last update.

【RubyonRails】外部キー制約のついたカラムを追加する

Posted at

はじめに

環境
- Ruby 2.6.3
- MySQL5.7

やりたいこと

旅館のオフィス活用マッチングを作成中
ユーザーがホテルをお気に入り登録できるようにしたい
なお、hotel_favoriteはモデル作成済み。

方法

hotel_favoriteモデルに、user_idとhotel_idを持たせたい。
(user_idは関連付け済み)

やったこと

rails g migration AddhotelidTohotel_favorites

→XXXXXXX_add_hotel_ref_tohotel_favorites.rbが作られた。
以下の通り編集しました。

XXXXXXX_add_hotel_ref_tohotel_favorites.rb
class AddHotelRefTohotelFavorites < ActiveRecord::Migration[6.0]
  def change
    add_reference :hotel_favorites, :hotel, null: false, foreign_key: true
  end
end

ここで

rails db:migrate

以下のように、hotel_favoriteにhotel_idが追加されました。

schema.rb
  create_table "hotel_favorites", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t|
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.bigint "user_id", null: false
    t.bigint "hotel_id", null: false
    t.index ["hotel_id"], name: "index_hotel_favorites_on_hotel_id"
    t.index ["user_id"], name: "index_hotel_favorites_on_user_id"

まとめ

次回からは、下の記事みたいに、モデル作成時点でやればいいですね。。
https://qiita.com/hiro266/items/8a0374155cd18adbd7cf

rails g model hotel_favorite user:references hotel:references
0
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
0
0