Help us understand the problem. What is going on with this article?

has_manyのdependentオプションについて【Ruby on Rails】

More than 1 year has passed since last update.

クラスの設定

投稿を行うPostと、それに対するコメントを行うCommentと仮定する。

class Post < ActiveRecord::Base
  has_many :comments
end
class Comment < ActiveRecord::Base
  belongs_to :post
end

この場合、親にあたる投稿が削除されたら(=Post::destroy()が呼ばれたら)子にあたるコメントの扱いをどうするか、というのがdependentオプションの趣旨である。

動作の確認

この場合、以下の4通りの動作がある。

has_many :comments, :dependent => :destroy
has_many :comments, :dependent => :delete_all

上2つはどちらもコメントを削除する動作だが、:destroyの場合はComment::destroy()を毎回呼ぶのに対し、:delete_allではdestroy()をスルーして直接削除するSQLとなる。

has_many :comments, :dependent => :nullify
has_many :comments

通常は:destroyを使う。大量の子があるような状況かつdestroy()で特に何もしてないような場合なら、:delete_allの方がパフォーマンスが高い。また、子が他のモデルとも紐づいているような場合は:nullifyを明示しないとおかしなことになるかもしれない。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away