在activeadmin上删除更快的300K关联对象(Rails 4,Activeadmin) [英] Delete faster 300K associated objects on activeadmin (Rails 4, Activeadmin)
问题描述
在创建模型交易时,我使用after_create在DealPrize表上创建奖品。
When creating a model Deal, I use an after_create to create prizes on the DealPrize table.
交易和DealPrize有一个属于/ has_many关系:一个交易具有
Deal and DealPrize have a belong to/has_many relations: a Deal has many Deal prizes and a Dealprize belongs to a Deal.
它的工作原理是:在Deal中,我有一个 prize-number列,并使用after_create,每次管理员创建新交易时,应用程序都会使用prize_number列,并在DealPrize表中创建此数量的奖品(根据需要插入尽可能多的行=>经常超过300,000)。
It works like this: inside Deal, I have a column 'prize-number' and I use an after_create so that every time the admin creates a new deal, the app takes this prize_number column, and create this volume of prizes (inserting as many rows as necessary=> often more than 300,000) inside the DealPrize table.
因此,我创建了一个交易,并且该应用程序自动创建了大量关联对象(奖品),例如300,000个。
So I create a Deal, and automatically, the app creates a huge number of associated objects (prizes) say 300,000.
问题是当我删除交易,我想删除所有相关的奖品。使用有效的管理员,我只需按删除即可,这要感谢 dependent::destroy 。 如果奖赏号码大约为200,则可以正常工作,但对于300K关联的对象/行,则非常慢。这需要15分钟。
The problem is when I delete the Deal, I want to delete all associated prizes. With active admin, I just press 'delete' and it works fine thanks to the dependent: :destroy. If the prize number is like 200, it works fine but for 300K associated objects/rows, it is very slow. It takes 15 minutes.
如何加快速度?我如何覆盖/增强ActiveAdmin删除功能以更快地删除300K关联的奖品?
我可以使用交易还是批量删除?
Could I use transactions or batched deletes ?
模态Deals.rb
has_many :deal_prizes, dependent: :destroy
after_create :create_deal_prizes
CONNECTION = ActiveRecord::Base.connection.raw_connection
def create_deal_prizes
begin
CONNECTION.describe_prepared('yokoatxz')
rescue PG::InvalidSqlStatementName
CONNECTION.prepare('yokoatxz', 'INSERT INTO deal_prizes (deal_id,created_at,updated_at,admin_user_id) values ($1, $2, $3, $4)')
end
Deal.transaction do
self.prizes_number.times do |i|
CONNECTION.exec_prepared('yokoatxz', [ { value: self.id},
{ value: '2009-01-23 20:21:13' },
{ value: '2009-01-23 20:21:13' },
{ value: self.admin_user_id }
] )
end
end
end
感谢您的帮助,
Mathieu
Thanks for your help, Mathieu
推荐答案
您会发现:
has_many :deal_prizes, dependent: :delete_all
...会更快,因为它会发出一条SQL语句:
... would be much faster, as it would issue a SQL statement to:
delete from deal_prizes where deal_id = 123;
不会进行回调,但这只是性能魔术的全部。
No callbacks would be made, but that's just all part of the performance magic.
请参阅: Rails:dependent => :destroy VS:dependent => :delete_all
这篇关于在activeadmin上删除更快的300K关联对象(Rails 4,Activeadmin)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!