LoginSignup
86
49

More than 1 year has passed since last update.

dependentオプションまとめ[Ruby on Rails]

Last updated at Posted at 2019-12-01

はじめに

userが複数のpostを持っていると仮定する

class User < ActiveRecord::Base
  has_many :posts
end
class Post < ActiveRecord::Base
  belongs_to :user
end

ここで、userが削除された場合、userに紐づいているpostsをどうするかをdependentオプションで指定できる

userと一緒にpostsを削除する場合

パターン1
class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
end
  • 基本これを覚える
  • ActiveRecordを介して削除(コールバック処理が実行される)
  • クエリがuserに紐づいているpostsの数だけ実行される
パターン2
class User < ActiveRecord::Base
  has_many :posts, dependent: :delete_all
end
  • SQLを直接実行して削除(コールバック処理は実行されない)
  • クエリが1回実行される

userだけ削除する(postsは削除しない)場合

class User < ActiveRecord::Base
  has_many :posts, dependent: :nullify
end
  • postsレコードのuser_idをnull更新する

エラーメッセージを表示させる場合

例えば、「postsを持っているuserなので、退会できません」などのエラーメッセージを出したい時などに便利

class User < ActiveRecord::Base
  has_many :posts, dependent: :restrict_with_error
end
  • userレコードにエラー情報(ActiveRecordのerror)が付加される
  • user.destroy でfalseを返す

例外を発生させる場合

class User < ActiveRecord::Base
  has_many :posts, dependent: :restrict_with_exception
end
  • DeleteRestrictionErrorがraiseする

参考情報

86
49
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
86
49