5
5

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 2018-09-04

アソシエーションとは

Ruby on RailsのActive Recordでテーブル間(モデル)の関連付けを行うこと

メソッドの種類

belongs_to...(「1対1」のつながりを設定する)
has_one...(「1対1」のつながりを設定する。belongs_toとの違いは、他方のモデルのインスタンスをまるごと含んでいること)
has_many...(「1対多」のつながりを設定する場合によく使われる。)
has_many :through...(「多対多」のつながりを設定する場合によく使われる。この関連付けは、2つのモデルの間に「第3のモデル」(結合モデル)が介在する点が特徴)
has_one :through...(他方のモデルに対して「1対1」のつながりを設定。この関連付けは、2つのモデルの間に「第3のモデル」(結合モデル)が介在する点が特徴)
has_and_belongs_to_man...(他方のモデルと「多対多」のつながりを作成する。through:を指定した場合と異なり、第3のモデル(結合モデル)が介在しない)

ex.)twitterのような投稿アプリの時

スクリーンショット 2018-09-04 15.01.00.png

User一人に対してPostsにはUserが投稿した複数の情報が入っている。
UserとPostsを連携させるために使うメソッドがbelongs_toメソッドhas_manyメソッドだ。

英文で書くと、、、
user has many posts (userはpostsを所有する)
posts belongs to user (postsはuserに属する)

なのでUserモデルには

has_many :posts, dependent: :destroy 

Postsモデルには

belongs_to :user

を記入し連携させる

dependentオプションとは

モデルの親レコードを削除するときに子のレコードを削除するかどうかを決めるオプション。

種類

オプション 説明
:destroy 親レコードと一緒に子レコードを削除。子レコードのコールバックも実行
:delete_all 親レコードと一緒に子レコードを削除。SQL直接実行なのでコールバックなし
:nullify 子レコードの外部キーをNULL更新する
:restrict_with_exception 子レコードがある場合はActiveRecord::DeleteRestrictionErrorを発生
:restrict_with_error 子レコードがある場合は削除が失敗し、親レコードにエラー情報を付与

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?