在搜索了几个小时的最佳实践之后,我来到了这里。
我有一个新的Foo对象,并且希望为它分配数千条,我已经预先加载了这些条:
@foo = Foo.create
@bars = Bar.find_all_by_some_attribute(:a)最快的方法是什么?我试过:
@foo.bars = @bars
@foo.bars << @bars这将导致创建数千个insert查询。
有解决我的问题的Rails 6 (Insert_all)方法吗?还是必须使用"m2m_fast_insert“gem或硬编码的SQL?来解决它?
发布于 2020-04-09 14:15:36
如果您有一个连接表设置,例如:
class Item < ActiveRecord::Base
has_and_belongs_to_many :orders
end
class Order < ActiveRecord::Base
has_and_belongs_to_many :items
end
class ItemsOrders < ActiveRecord::Base
belongs_to :item
belongs_to :order
end我相信您可以在本例中(或您的连接模型是什么)中插入许多ItemOrders,insert_all是Rails 6中的新特性。如果不是,最好的选择是一定量的自定义SQL。我确实在上面找到了另一个答案,这似乎是SQL:What is the fastest way to create mass HABTM associations in Rails?的一个很好的起点。
https://stackoverflow.com/questions/61103249
复制相似问题