Search code examples
ruby-on-railsnesteddestroy

ruby on rails Nested structure not deleting the related objects


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?


Solution

  • You can use dependent: :delete_all