同一モデルへの関連に対するdependentオプション

いつ書いたのか忘れたけど、下書きに書いてあったので公開

次のように、同じモデルに対してdependent: :destroyを設定してしまうと、もとのモデルを削除したときに二重にDELETEが発行されてしまう

class User < ApplicationRecord
  has_one :latest_post, -> { order(created_at: :desc) }, class_name: 'Post', dependent: :destroy
  has_many :posts, dependent: :destroy
end
 user.destroy
   (0.1ms)  begin transaction
  Post Load (0.3ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."user_id" = ? ORDER BY "posts"."created_at" DESC LIMIT ?  [["user_id", 1], ["LIMIT", 1]]
  Post Destroy (0.4ms)  DELETE FROM "posts" WHERE "posts"."id" = ?  [["id", 2]]
  Post Destroy (0.1ms)  DELETE FROM "posts" WHERE "posts"."id" = ?  [["id", 1]]
  Post Destroy (0.1ms)  DELETE FROM "posts" WHERE "posts"."id" = ?  [["id", 2]]
  User Destroy (0.1ms)  DELETE FROM "users" WHERE "users"."id" = ?  [["id", 1]]
   (0.8ms)  commit transaction

dependent: :destroyは片方だけにしておいたほうがよさそう