0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アソシエーションについてまとめてみた

Last updated at Posted at 2019-05-22

##アソシエーション(関連付け)
アソシエーションとは、モデルとDB間をまたいだデータの呼び出しをより簡単に行うことが出来る。
####アソシーションの定義
①モデルクラスにhas_manyやbelongs_toが定義されていること。
②所属するテーブル側に、クラス名_idというカラムがあること。

####用語の解説
※分かりやすくするために、ツイッターを例に解説します。

has_many → ユーザーは、自分の作成したツイートを複数個所持している状態である。

qiita.rb
class User < ApplicationRecord
    devise :database_authenticatable, :registerable,
           :recoverable, :rememberable, :validatable
    has_many :tweets
  end

belongs_to →全てのユーザーは、いずれかのツイートを保持している。

qiita.rb
class Tweet < ApplicationRecord
    belongs_to :user
  end

####アソシエーションのメリット
・モデルをまたいだ呼び出しが簡単になる。
 →userモデルのインスタンス.tweetsで呼び出しが可能になる

・アソシエーションを使用しない

ターミナル
[2] pry(main)> Tweet.where(user_id: user.id)

・アソシエーションを使用

ターミナル
[2] pry(main)> user.tweets
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?