LoginSignup
51
41

More than 5 years have passed since last update.

[Rails] has_manyおよびbelongs_toへのdependent: :destroyの設定について

Last updated at Posted at 2019-04-23

問題

User has_many Cup(s)といった関連のなかで、
Cup.destroyをしたところUserまでも消えてしまった。

理由については本記事を見てもらえればわかるが、
dependent: :destroyの付与について時折迷うことがあったので
備忘録として残しておく。

対処

以下のような関連があるとする。

User
User has_many Cup(s)

Cup
Cup belongs_to User

この関連に対し、dependent: :destroyを以下のように設定していた。

Class User < ApplicationRecord
  has_many :cups, dependent: :destroy
end
class Cup < ApplicationRecord
  belongs_to :user, dependent: :destroy
end

この状態でCup(のインスタンス)をdestroyしたところ、
そのユーザまでもが削除されてしまった。


そこで下記のようにbelongs_toからdependent: :destroy
消去したところ、Cupを消してもそのユーザは残ったままになった。

Class User < ApplicationRecord
  has_many :cups, dependent: :destroy
end
class Cup < ApplicationRecord
  belongs_to :user
end

:dependentの付与の仕方

has_manybelongs_toどちらにdependent: :destroyをつけるか迷う時があるが、上記より、

dependent: :destroy指定したクラスが消えた場合に、
dependent: :destroy設定したモデル(のインスタンス)がdestroyされる

ということになる。

具体例

class Cup < ApplicationRecord
  belongs_to :user, dependent: :destroy
end

このコードでは、

dependent: :destroy指定したクラスCup
dependent: :destroy設定したモデル(のインスタンス)user

となるので、Cupが消えるとUserが消えることになる。


Class User < ApplicationRecord
  has_many :cups, dependent: :destroy
end

このコードでは、

dependent: :destroy指定したクラスUser
dependent: :destroy設定したモデル(のインスタンス)cups

となるので、Userが消えるとCup(s)が消えることになる。


おわり

51
41
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
51
41