gpt4 book ai didi

ruby-on-rails - 通过与 :dependent => :destroy Rails 3. 2 的关系删除 has_many 中的对象

转载 作者:搜寻专家 更新时间:2023-10-30 22:02:05 25 4
gpt4 key购买 nike

我正在开发一个 Rails 应用程序,用户可以在其中创建项目。有两种类型的用户 AdminsCollaborators。管理员和协作者 has_many :accounts, through: :account_users,其中 account_users 是一个连接表。当管理员删除他们的帐户时,我也想删除他们创建的帐户及其项目,但我无法让它工作。我的模型目前看起来像这样:

class Collaborator < User
[...]
has_many :account_users
has_many :accounts, through: :account_users
[...]
end

class Admin < User
has_many :account_users
has_many :accounts, through: :account_users, :dependent => :destroy
[...]
end

class Account < ActiveRecord::Base
[...]
belongs_to :admin
has_many :account_users
has_many :collaborators, through: :account_users
[...]
end


class AccountUser < ActiveRecord::Base
belongs_to :admin
belongs_to :account
belongs_to :collaborator
end

当管理员用户删除其帐户时,只会删除连接表和用户表中的行,不会删除他们的项目。

请注意,我使用设计来处理身份验证。

我该如何解决这个问题?

最佳答案

我没有看到项目关联,所以我认为您可以通过以下两种方式之一进行:

class Account < ActiveRecord::Base
after_save :destroy_projects

private
def destroy_projects
self.projects.delete_all if self.destroyed?
end
end

class Account < ActiveRecord::Base
[...]
belongs_to :admin
has_many :account_users
has_many :collaborators, through: :account_users
has_many :projects, :dependent => :destroy
[...]
end

关于ruby-on-rails - 通过与 :dependent => :destroy Rails 3. 2 的关系删除 has_many 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com