shaan
shaan

Reputation: 524

Can we insert multiple row in one query in Ruby on Rails ActiveRecord?

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

Answers (3)

Marian13
Marian13

Reputation: 9308

insert_all (Rails 6+)

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

Sandeep Garg
Sandeep Garg

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

srinij
srinij

Reputation: 195

check activerecord-import gem, it allows to insert in the bulk.

Upvotes: 3

Related Questions