Ruby on Rails的嵌套结构不删除相关的对象
问题描述:
用户模型Ruby on Rails的嵌套结构不删除相关的对象
class User < ApplicationRecord
has_many :posts
accepts_nested_attributes_for :posts, allow_destroy: true
end
桩模型
class Post < ApplicationRecord
belongs_to :user
accepts_nested_attributes_for :user, allow_destroy: true
end
用户控制器
class Api::UsersController < ApiController
def destroy
User.destroy(params[:id])
end
end
我想如果我毁使用破坏用户,所有与用户相关的帖子都将被自动删除。
但仍然没有被删除。 我在这里做错了什么?
答
您可以使用dependent: :delete_all
答
has_many :posts, :dependent => :delete_all
+0
没有任何倾销码解释并不是一个很好的答案格式 –
嗨,看看这个帖子,请https://*.com/questions/29560805/how-to-use-dependent-destroy-in-rails – zauzaj