LoginSignup
1

More than 5 years have passed since last update.

Rails アソシエーションのhas_many・belongs_toについてまとめてみた

Last updated at Posted at 2018-10-18

アソシエーションとは

2種類のテーブルを関連付けさせること。
関連付けをすることにより、簡潔にコードをまとめることができます。
テーブル同士の関係には、「1:1」「1:多」「多:多」の3つの関係があります。
今回は「1:1」「1:多」の関係を表す時に使われるアソシエーションの「has_many」「belongs_to」
をまとめてみました。

has_many

◯◯が複数の△△を所有しているという関係を表す時に使うアソシエーション。

belongs_to

△△が◯◯に従属するという関係を表す時に使うアソシエーション。

使い方

user登録ができる投稿アプリの場合

user.rb
class User < ApplicationRecord
  has_many :posts, dependent: :destroy
end
post.rb
class Post < ApplicationRecord
  belongs_to :user
end
@user.destroy

上記のように関連付けしたことで、user情報と、そのuserの投稿をまとめて削除するコードを簡潔に書くことができます。

参考サイト

Active Record の関連付け (アソシエーション) | Rails ガイド
Rails モデルの関連付け(アソシエーション) - Qiita
【Rails入門】has_many、belongs_toの使い方まとめ

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