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
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 Columns (1.1ms) SHOW FIELDS FROM
bars_foos
SQL (0.6ms) INSERT INTObars_foos
(bar_id
,foo_id
) VALUES (100, 117200)
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.
Do I need to write the SQL, or does Rails have a prettier way?