什么是建立在Rails的质量HABTM协会的最快方法是什么? [英] What is the fastest way to create mass HABTM associations in Rails?
问题描述
我有两个表,在Rails的一个HABTM关系。类似如下:
I have two tables, with a HABTM relationship in Rails. Something like the following:
class Foo < ActiveRecord::Base
has_and_belongs_to_many :bars
end
class Bar < ActiveRecord::Base
has_and_belongs_to_many :foos
end
现在我有一个新的富
对象,并希望大众分配几千条吧,我已经pre装:
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
和两个运行速度很慢,用类似下面的每个栏
的条目:
And both run really slow, with an entry like the following for each bar
:
bars_foos列(1.1ms)SHOW
FIELDS FROM bars_foos
SQL(0.6ms)
INSERT INTO bars_foos
( bar_id
,
foo_id
)VALUES(100,117200)
bars_foos Columns (1.1ms) SHOW FIELDS FROM
bars_foos
SQL (0.6ms) INSERT INTObars_foos
(bar_id
,foo_id
) VALUES (100, 117200)
我看着AR-扩展,但进口
功能似乎并不没有一个模型(Model.import),其中$ P $工作pcludes其使用了连接表。
I looked at ar-extensions, but the import
function doesn't seem to work without a model (Model.import) which precludes its use for a join table.
我是否需要写SQL,还是Rails的有prettier方式?
Do I need to write the SQL, or does Rails have a prettier way?
推荐答案
我认为最好的性能代价将是使用SQL和批量插入多行每次查询。如果你可以建立做类似的INSERT语句:
I think your best bet performance-wise is going to be to use SQL, and bulk insert multiple rows per query. If you can build an INSERT statement that does something like:
INSERT INTO foos_bars (foo_id,bar_id) VALUES (1,1),(1,2),(1,3)....
您应该能够插入数千行的一个查询。我没有尝试你mass_habtm方法,但好像你可能喜欢的东西:
You should be able to insert thousands of rows in a single query. I didn't try your mass_habtm method, but it seems like you could to something like:
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搜索栏,请确保您的数据库有一个字段建立索引。
Also, if you are searching Bar by "some_attribute", make sure you have that field indexed in your database.
这篇关于什么是建立在Rails的质量HABTM协会的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!