我有与HABTM关系相关的轨道模型Article
和User
。 即一个User
可以有很多文章,一个Article
可以属于许多User
。 我很难删除记录。我的要求是:
- 任何其他用户无关的文章,我想完全删除该文章,这意味着,从
Article
表以及Article
与has_many
关联的所有其他表中删除文章(我有其他模型,如ArticleLinks
、ArticleMetaTags
等与Article
模型相关联(。 - 如果
Article
也与其他User
相关联,请不要完全删除该文章。只需删除User
并Article
关联即可。
感谢您的时间和帮助。
您始终可以在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