【发布时间】:2010-02-04 21:37:57
【问题描述】:
我有两个表,在 Rails 中有一个 HABTM 关系。类似于以下内容:
class Foo < ActiveRecord::Base
has_and_belongs_to_many :bars
end
class Bar < ActiveRecord::Base
has_and_belongs_to_many :foos
end
现在我有一个新的Foo 对象,并且想要批量分配数千条柱子,我已经预加载了:
@foo = Foo.create
@bars = Bar.find_all_by_some_attribute(:a)
最快的方法是什么?我试过了:
@foo.bars = @bars
@foo.bars << @bars
而且两者都运行得很慢,每个bar 的条目如下:
bars_foos 列 (1.1ms) 显示 来自
bars_foosSQL 的字段(0.6 毫秒) 插入bars_foos(bar_id,foo_id) 值 (100, 117200)
我查看了 ar-extensions,但如果没有模型 (Model.import),import 函数似乎无法工作,因为模型 (Model.import) 无法将其用于连接表。
我需要写 SQL,还是 Rails 有更漂亮的方式?
【问题讨论】:
-
真的吗?没有人?你们跳过上篮和“最佳实践”问题:)
标签: ruby-on-rails activerecord has-and-belongs-to-many