如何从 HABTM 关联中完全和部分删除记录



我有与HABTM关系相关的轨道模型ArticleUser。 即一个User可以有很多文章,一个Article可以属于许多User。 我很难删除记录。我的要求是:

如果用户删除与
  • 任何其他用户无关的文章,我想完全删除该文章,这意味着,从Article表以及Articlehas_many关联的所有其他表中删除文章(我有其他模型,如ArticleLinksArticleMetaTags等与Article模型相关联(。
  • 如果Article也与其他User相关联,请不要完全删除该文章。只需删除UserArticle关联即可。

感谢您的时间和帮助。

您始终可以在ArticleUser(连接模型(的before_destroy回调中实现它:

class ArticleUser
belongs_to :article
belongs_to :user
after_destroy do
article.destroy if article.article_users.empty?
end
end

如果没有,则需要创建它,并将has_and_belongs_to_many更改为has_many

class Article
has_many :article_users
has_many :users, through: :article_users
end
class User
has_many :article_users
has_many :articles, through: :article_users
end

这是更多的代码,但为您提供了更大的灵活性。

但我建议在一些服务类中实现它,例如:

class ArticleUsers::Delete
attr_accessor :article_user
def initialize(article_user)
self.article_user = article_user
end
def destroy
if article_user.destroy
article_user.article.destroy
end
end
end

然后在您需要的任何地方调用它ArticleUsers::Delete.new(article_user).destroy

作为预防措施,如果您没有任何用于删除文章的显式逻辑,则可以Article类中的article_users关联添加restrict_with_exception。如果存在任何关联的记录,则会导致引发异常。

class Article
has_many :article_users, dependent: :restrict_with_exception
end

最新更新