LoginSignup
3
3

More than 3 years have passed since last update.

has_manyとbelongs_toの使い方

Last updated at Posted at 2020-08-01

プログラミングの勉強日記

2020年8月2日 Progate Lv.226
has_manybelongs_toの使い分けに戸惑った。has_manyのときに複数形にするのを忘れてしまい、うまく実行されなかったので、has_manybelongs_toについてまとめる。

関連付け(アソシエーション)とは

 2つのテーブルを関連付けさせること。テーブル間の関係をモデル上の関係として操作する仕組み。
 テーブル同士の関係には「1:1」「1:多」「多:多」の3つの関係が存在する。今回は「1:1」「1:多」の関係を表すときに使うhas_manybelongs_toについてまとめる

 今回は、UserテーブルのidをPostテーブルと関連付けをして、誰の投稿かわかるようする。

has_manyとは

 has_manyは「1:多」の関連付けを表し、〇〇が複数の〇〇を所有しているという関係を表す時に使う。関連付けをすることによって、データをまとめて扱えるようになるので、より効率的にデータベースを操作することができる。

models/user.rb
class User < ApplicationRecord
  has_many :posts
end

 has_manyを使うときは複数形にする

belongs_toとは

 belongs_toは「1:1」の関連付けを表し、〇〇が◯◯に従属するという関係を表す時に使う。

models/post.rb
class Post < ApplicationRecord
  belongs_to :user
end

 belongs_toを使うときは単数形にする

 

3
3
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
3
3