LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】 モデルをreferencesで関係づける

Last updated at Posted at 2021-04-02

はじめに

この記事はrailsで扱うモデルの関係性について書いています
referencesを使い親モデルが削除されたら子モデルも削除されるようにモデルの対応を行う。


今回はdeviseのUserとGroupモデルを作成し
user:group=1:Nの形にする
13822235635078.jpg


この記事を読むに当たりdeviseを使ったUserモデルは作成しているとし省略する。
Userモデルを作っていない人は以下の記事を参考にUserモデルを作成してほしい。

Groupモデルの作成

ターミナルで以下のコマンドを入力する

ターミナル
$ rails g model group

そしたらマイグレーションファイルが作られているので編集する

db/migrate/----create_groups.rb
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

t.references :user, null:false,foreign_key:true
はuserモデルを親としgroupを子とする。また空欄は許容されない。これによって親と子の関係が作れる。
このように編集できたら rails db:migrateを行う

ターミナル
$ rails db:migrate

これでモデルが作成されている。
確認の仕方はdb/schema.rbを見る

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を開き編集する

models/group.rb
class Group < ApplicationRecord
  belongs_to :user
end

このように書くことでGroupモデルはuserに関連付けられる。
belongs_toを書くときは必ず単数形の形で書くbelongs_to:user

次にuserモデルについて編集する

models/user.rb
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も削除してくれる機能である

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