如何从 HABTM 协会中完全或部分删除记录

How do I delete records completely and partially from HABTM association

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

感谢您的宝贵时间和帮助。

您始终可以在 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,例如:

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 class 中添加 restrict_with_exceptionarticle_users 关联.如果有任何关联的记录,它会引发异常。

class Article
  has_many :article_users, dependent: :restrict_with_exception
end