gpt4 book ai didi

ruby-on-rails - ActiveRecord 事务,保存 1000+ 条目

转载 作者:行者123 更新时间:2023-12-02 22:11:57 24 4
gpt4 key购买 nike

我让 EventsController 创建如下所示的操作:

class EventsController < ApplicationController

def create
@event = Event.new(params[:event].slice(*Event.accessible_attributes))
if @event.save
DraftBuilder.new(event: @event).build(params[:event][:file].path)
redirect_to @event
else
render :new
end
end

end

params[:event][:file] 是用户可以通过 file_field_tag 通过 Event#new 操作提交的文件。

DraftBuilder#build 方法,除其他外,解析给定文件并在数据库中创建大约 1000 条记录(跨多个表将数据保存到数据库)。

我遇到的问题是 DraftBuilder#build 真的很慢。它很慢,因为我在循环中保存记录并且 Active Record 为每次保存创建新的事务。

简化的 DraftBuilder#build 可能如下所示:

class DraftBuilder
def build(file)
@data = parse(file) #@data is an array of hashes with 1000+ records
@data.each do |pick_arguments|
Pick.create(pick_arguments)
end
end
end

我找到了解决这个问题的方法。将 Controller 创建操作包装到 ActiveRecord::Base.transaction:

class EventsController < ApplicationController
around_filter :transactions_filter, only: [:create]

def transactions_filter
ActiveRecord::Base.transaction do
yield
end
end
end

虽然此解决方案有效,但只创建了一个事务,整个过程的速度提高了大约 60 倍。这是解决这个问题的好方法吗?交易肯定不是为此设计的?从包含超过 1000 个条目的文件创建记录的其他选项是什么?

最佳答案

运行缓慢的进程的最佳解决方案是使用后台作业,如 delayed_jobresquesidekiq .

关于ruby-on-rails - ActiveRecord 事务,保存 1000+ 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com