3

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This solution, while it does work, fires a single INSERT query for each record you are inserting. The benefit is that you get all your *_save and/or *_create modal callbacks for each record (whereas doing a raw SQL INSERT for your n rows bypasses your model logic). The cost, however, is that your query turns into n queries and the overall action is much slower. Probably a good reason to practice pushing business logic into the DB when and where possible!
4

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

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.