我如何在直接的 postgresql 中编写这个 ruby rake 任务?
How do I write this ruby rake task in straight postgresql?
这里是 rake 任务:
task :map_comment_to_user => :environment do
Comment.all.each do |c|
a = Admin.where(mongo_id: c.mongo_user_id).first
u = User.where(email: a.email).first
c.user_id = u.id
c.save
end
end
我搞砸了从 Admin => User 表的迁移,而且电子邮件是独一无二的,这让我可以将它们拼接起来。但是太慢了。
如何在直接的 PSQL 中编写上面的内容?
UPDATE comments c
SET c.user_id = u.id
FROM users u admins a
WHERE c.mongo_user_id == a.mongo_id
AND u.email = a.email; ???
这可以为您节省大量的对象初始化成本并加快速度。
Comment.select(:id,:user_id).each do |c|
email = Admin.where(mongo_id: c.mongo_user_id).pluck(:email).first
uid = User.where(email: email).pluck(:id).first
c.user_id = uid
c.save
end
您的 SQL 非常接近。它只需要一些小的语法更改。
UPDATE comments c
SET user_id = u.id
FROM users u, admins a
WHERE c.mongo_user_id = a.mongo_id
AND u.email = a.email;
这里是 rake 任务:
task :map_comment_to_user => :environment do
Comment.all.each do |c|
a = Admin.where(mongo_id: c.mongo_user_id).first
u = User.where(email: a.email).first
c.user_id = u.id
c.save
end
end
我搞砸了从 Admin => User 表的迁移,而且电子邮件是独一无二的,这让我可以将它们拼接起来。但是太慢了。
如何在直接的 PSQL 中编写上面的内容?
UPDATE comments c
SET c.user_id = u.id
FROM users u admins a
WHERE c.mongo_user_id == a.mongo_id
AND u.email = a.email; ???
这可以为您节省大量的对象初始化成本并加快速度。
Comment.select(:id,:user_id).each do |c|
email = Admin.where(mongo_id: c.mongo_user_id).pluck(:email).first
uid = User.where(email: email).pluck(:id).first
c.user_id = uid
c.save
end
您的 SQL 非常接近。它只需要一些小的语法更改。
UPDATE comments c
SET user_id = u.id
FROM users u, admins a
WHERE c.mongo_user_id = a.mongo_id
AND u.email = a.email;