#はじめに
この記事はrailsで扱うモデルの関係性について書いています
referencesを使い親モデルが削除されたら子モデルも削除されるようにモデルの対応を行う。
今回はdeviseのUserとGroupモデルを作成し
user:group=1:Nの形にする
この記事を読むに当たりdeviseを使ったUserモデルは作成しているとし省略する。
Userモデルを作っていない人は以下の記事を参考にUserモデルを作成してほしい。
#Groupモデルの作成
ターミナルで以下のコマンドを入力する
$ rails g model group
そしたらマイグレーションファイルが作られているので編集する
class CreateGroups < ActiveRecord::Migration[6.1]
def change
create_table :groups do |t|
t.string :name, null: false
t.references :user, null: false,foreign_key: true
t.timestamps
end
end
end
```はuserモデルを親としgroupを子とする。また空欄は許容されない。これによって親と子の関係が作れる。
このように編集できたら ```rails db:migrate```を行う
```:ターミナル
$ rails db:migrate
これでモデルが作成されている。
確認の仕方はdb/schema.rbを見る
create_table "groups", force: :cascade do |t|
t.string "name", null: false
t.integer "user_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["user_id"], name: "index_groups_on_user_id"
end
これを見てみるとname
の他にuser_id
というカラムが作られていることが分かる。
#それぞれのモデルの関係性を記入する
モデルが作れたら次はuser:groupの1:Nの関係を作る
まずmodels/group.rb
を開き編集する
class Group < ApplicationRecord
belongs_to :user
end
このように書くことでGroupモデルはuserに関連付けられる。
belongs_to
を書くときは必ず単数形の形で書くbelongs_to:user
次にuserモデルについて編集する
class User < ApplicationRecord
has_one_attached :image
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many:groups, dependent: :destroy
end
has_many:groups, dependent: :destroy
と書くことで1:Nの関係が作れる。
has_one
にすることで1:1の関係にすることができる。
ただしhas_many
の場合は複数形groups,
has_one
の場合は単数形groupにする。
dependent: :destroy
はUserが削除されたらそのUserに関連しているGroupも削除してくれる機能である