简体   繁体   English

Rails:如何在销毁用户时销毁所有用户的帖子

[英]Rails: How to destroy all user's posts when user is destroyed

Currently I have a SuperAdmin who can destroy users and posts . 目前,我有一个可以销毁userspostsSuperAdmin

However, there's a problem when destroying users. 但是,销毁用户时会出现问题。 Since all the user's old post still exist, there's a bunch of posts left with blank users. 由于所有用户的旧帖子仍然存在,因此有一堆空白用户的帖子。 Errors ensue. 随之而来的错误。

Would you know how to code it so that when the user is destroyed, all posts of that user are also destroyed? 您是否知道如何编码,以便在销毁用户时也销毁该用户的所有帖子? Here is what I'm using in the SuperAdmin controller. 这是我在SuperAdmin控制器中使用的东西。

class SuperAdminController < ApplicationController
  layout 'super_admin'
  before_action :authenticate_super_admin!
end  


  def destroy
    @user = User.find(params[:id])
    @user.destroy

    if @user.destroy
        redirect_to :back, notice: "User deleted."
    end
  end

Thanks in advance and for your patience. 在此先感谢您的耐心配合。 I am new to coding. 我是编码新手。

use the dependent option on the association. 在关联上使用dependent选项。

here is an example of a model definition. 这是模型定义的示例。 when you delete a post, its assets will be deleted as well, as part of the dependent association: 删除帖子时,其资产也将被删除,作为从属关联的一部分:

class Post < ActiveRecord::Base
  has_many :assets, dependent: :destroy
end

source: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html 来源: http : //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM