0

user model

class User < ApplicationRecord
  has_many :posts
  accepts_nested_attributes_for :posts, allow_destroy: true
end

post model

class Post < ApplicationRecord
  belongs_to :user
  accepts_nested_attributes_for :user, allow_destroy: true
end

user controller

class Api::UsersController < ApiController
  def destroy
    User.destroy(params[:id])
  end
end

I thought if I destroy the user using destroy, all the posts related to user will be deleted automatically.

But still nothing is deleted. What I am doing wrong here?

Pig and Cat
  • 140
  • 3
  • 17
  • Hi, check this post please https://stackoverflow.com/questions/29560805/how-to-use-dependent-destroy-in-rails – zauzaj Sep 26 '17 at 11:20

2 Answers2

1

You can use dependent: :delete_all

HM Tanbir
  • 990
  • 12
  • 30
0
has_many :posts, :dependent => :delete_all
Sai Ram Reddy
  • 1,079
  • 13
  • 14