[英]Rails remove duplicated associated records
Let's say I have a User
and User has_many :tags
and I would like to remove all @users
tags that have duplicated name
. 假设我有一个User
和一个用户has_many :tags
,我想删除所有name
重复的@users
标签。 For example, 例如,
@user.tags #=> [<Tag name: 'A'>, <Tag name: 'A'>, <Tag name: 'B'>]
I would like to keep only the tags with unique names and delete the rest from the database. 我只想保留具有唯一名称的标签,并从数据库中删除其余的标签。
I know I could pull out a list of unique tags names from user's tags and remove all users's tags and re-create user's tags with only unique names but it would be ineffficient? 我知道我可以从用户标签中提取出唯一标签名称列表,然后删除所有用户标签,然后仅使用唯一名称重新创建用户标签,但这效率低下吗?
On the other hand, select
won't work as it returns only the selected column. 另一方面, select
将不起作用,因为它仅返回选定的列。 uniq
also won't work: uniq
也将不起作用:
@user.tags.uniq #=> returns all tags
Is there a more efficient way? 有没有更有效的方法?
UPDATE: I would like to do this in a migration. 更新:我想在迁移中做到这一点。
This method will give you an ActiveRecord::Relation with the duplicate tags: 此方法将为您提供带有重复标签的ActiveRecord :: Relation:
class Tag < ApplicationRecord
belongs_to :user
def self.duplicate_tags
unique = self.select('DISTINCT ON(tags.name, tags.user_id) tags.id')
.order(:name, :user_id, :id)
self.where.not(id: unique)
end
end
Its actually run as a single query: 它实际上是作为单个查询运行的:
SELECT "tags".* FROM "tags"
WHERE "tags"."id" NOT IN
(SELECT DISTINCT ON(tags.name) tags.id
FROM "tags" GROUP BY "tags"."id", "tags"."user_id"
ORDER BY tags.name, tags.id)
You can remove the duplicates in a single query with #delete_all
. 您可以使用#delete_all
在单个查询中删除重复#delete_all
。
# Warning! This can't be undone!
Tag.duplicate_tags.destroy_all
If you need to destroy dependent associations or call your before_*
or after_destroy
callbacks, use the #destroy_all
method instead. 如果您需要销毁相关联的关联或调用before_*
或after_destroy
回调,请改用#destroy_all
方法。 But you should use this together with #in_batches
to avoid running out of memory. 但是您应该将其与#in_batches
一起使用,以免耗尽内存。
# Warning! This can't be undone!
Tag.duplicate_tags.in_batches do |batch|
# destroys a batch of 1000 records
batch.destroy_all
end
You can write SQL model-independent query in the migration. 您可以在迁移中编写与SQL模型无关的查询。 Here is PostgreSQL-specific migration code: 这是特定于PostgreSQL的迁移代码:
execute <<-SQL
DELETE FROM tags
WHERE id NOT IN (
SELECT DISTINCT ON(user_id, name) id FROM tags
ORDER BY user_id, name, id ASC
)
SQL
And here is more SQL common one: 这是更常见的SQL:
execute <<-SQL
DELETE FROM tags
WHERE id IN (
SELECT DISTINCT t2.id FROM tags t1
INNER JOIN tags t2
ON (
t1.user_id = t2.user_id AND
t1.name = t2.name AND
t1.id < t2.id
)
)
SQL
This SQL fiddle shows different queries you can use as sub-select in DELETE
query depending on your goals: deleting first/last/all duplicates. 此SQL小提琴显示了不同的查询,您可以根据自己的目标在DELETE
查询中用作子选择 :删除第一个/最后一个/所有重复项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.