gpt4 book ai didi

ruby-on-rails - 如何使用 rails 事件记录批量插入所有嵌套属性

转载 作者:行者123 更新时间:2023-11-29 14:02:59 26 4
gpt4 key购买 nike

我有一个这样的报告模型:-

class Report < ActiveRecord::Base
has_many :report_clients
accepts_nested_attributes_for :report_clients, :reject_if => proc { |attributes| attributes['client_id'].blank? }, :allow_destroy => true
end

报告客户端模型就像

class ReportClient < ActiveRecord::Base
belongs_to :report
end

在创建报告时,我的参数结构如下

Report.create({name: params[:name],  report_clients_attributes: [{client_id: 1}, {client_id:2}]})

它将运行 1 个查询以插入报告,并运行 2 个查询以插入 report_clients。

通常我会针对每个报告插入 1000 个 report_clients,这会导致 1000 个 sql 查询。

我知道,我可以通过编写原始 sql 插入来解决使用批量插入的问题。但是想知道是否有其他方法/更好的方法来做到这一点。

最佳答案

经历过类似的场景,有一个很棒的 gem activerecord-import对于这些类型的案例。

report = Report.new(name: params[:name])
report.save_with_nested_attributes(report_clients_attributes)

report.rb

def save_with_nested_attributes(report_clients_attributes)
report_clients_objects = []
transaction do
save!
report_clients_attributes.each do |client_attributes|
report_clients_objects << report_clients.new(client_attributes)
end
ReportClient.import(report_clients_objects)
end
end

gem wiki中提到了很多其他方式批量导入记录。

希望对您有所帮助!

关于ruby-on-rails - 如何使用 rails 事件记录批量插入所有嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38369515/

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