如何从 HABTM 协会中完全或部分删除记录
How do I delete records completely and partially from HABTM association
我有 rails 个模型 Article
和 User
与 HABTM 关系相关联。即一个 User
可以有很多文章,一个 Article
可以属于许多 User
。
我很难删除记录。我的要求是:
- 如果用户删除了与任何其他用户无关的文章,我想完全删除该文章,意思是,从
Article
table 以及所有其他 tables 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,例如:
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_exception
到 article_users
关联.如果有任何关联的记录,它会引发异常。
class Article
has_many :article_users, dependent: :restrict_with_exception
end
我有 rails 个模型 Article
和 User
与 HABTM 关系相关联。即一个 User
可以有很多文章,一个 Article
可以属于许多 User
。
我很难删除记录。我的要求是:
- 如果用户删除了与任何其他用户无关的文章,我想完全删除该文章,意思是,从
Article
table 以及所有其他 tablesArticle
与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,例如:
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_exception
到 article_users
关联.如果有任何关联的记录,它会引发异常。
class Article
has_many :article_users, dependent: :restrict_with_exception
end