Reputation: 524
Hi below in a given scenario
some_model_id = [1, 2, 3, 4]
some_model_id.each do |some_id|
SomeOtherModel.create(some_column: some_id)
end
Here insert
query will run n
times depending on some_model_id
size
Is there a way where I can do it in single query on some other better approach then this.
Upvotes: 3
Views: 4771
Reputation: 9308
Starting from Rails 6
, ActiveRecord
supports inserting multiple rows using one SQL query out of the box.
Please, have a look at insert_all
Upvotes: 4
Reputation: 1276
ActiveRecord create can also take array of insert statement which will formulate only single ActiveRecord object but it still execute multiple insert statement in database. Refer following code
SomeOtherModel.create([{some_column: some_id}, {some_column: some_id}, {some_column:some_id}])
To insert multiple record at once it is better to use raw SQL insert command with multiple values.
Upvotes: 5