gpt4 book ai didi

ruby-on-rails - 在 Rails 中创建大量 HABTM 关联的最快方法是什么?

转载 作者:行者123 更新时间:2023-12-03 20:49:45 25 4
gpt4 key购买 nike

我有两个表,在 Rails 中有一个 HABTM 关系。类似于以下内容:

class Foo < ActiveRecord::Base
has_and_belongs_to_many :bars
end

class Bar < ActiveRecord::Base
has_and_belongs_to_many :foos
end

Now I have a new Foo object, and want to mass-assign thousands of bars to it, which I've pre-loaded:

@foo = Foo.create
@bars = Bar.find_all_by_some_attribute(:a)

What's the fastest way to do this? I've tried:

@foo.bars = @bars
@foo.bars << @bars

并且两者都运行得非常慢,每个 bar 的条目如下所示。 :

bars_foos Columns (1.1ms) SHOW FIELDS FROM bars_foos SQL (0.6ms) INSERT INTO bars_foos (bar_id, foo_id) VALUES (100, 117200)



我查看了 ar-extensions,但 import如果没有模型 (Model.import),函数似乎无法工作,这会阻止其用于连接表。

我需要编写 SQL,还是 Rails 有更漂亮的方法?

最佳答案

我认为在性能方面最好的选择是使用 SQL,并为每个查询批量插入多行。如果您可以构建一个执行以下操作的 INSERT 语句:

INSERT INTO foos_bars (foo_id,bar_id) VALUES (1,1),(1,2),(1,3)....

您应该能够在单个查询中插入数千行。我没有尝试您的 mass_habtm 方法,但您似乎可以这样做:
bars = Bar.find_all_by_some_attribute(:a)
foo = Foo.create
values = bars.map {|bar| "(#{foo.id},#{bar.id})"}.join(",")
connection.execute("INSERT INTO foos_bars (foo_id, bar_id) VALUES #{values}")

此外,如果您通过“some_attribute”搜索 Bar,请确保您在数据库中对该字段进行了索引。

关于ruby-on-rails - 在 Rails 中创建大量 HABTM 关联的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2203420/

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