How Would I Save Multiple Records at Once in Rails

How would I save multiple records at once in Rails?

A nice solution is to use the active record import gem. I recommend it over now built-in Rails bulk insert because it's more flexible in the options in case of constraint violation.

TaxRate.import(
[:income_from, :income_to, :start, :finish, :rate, :premium],
tax_rates
)

Its definitely better than my old answer which would trigger a db commit per entry in the array :)


Old answer:

tax_rates.map {|tax_rate| TaxRate.new(tax_rate).save } 

This way you'll retrieve an Array with true or false to know which did succeed and which didn't.

Saving multiple objects in a single call in rails


insert_all (Rails 6+)

Rails 6 introduced a new method insert_all, which inserts multiple records into the database in a single SQL INSERT statement.

Also, this method does not instantiate any models and does not call Active Record callbacks or validations.

So,

Foo.insert_all([
{ first_name: 'Jamie' },
{ first_name: 'Jeremy' }
])

it is significantly more efficient than

Foo.create([
{ first_name: 'Jamie' },
{ first_name: 'Jeremy' }
])

if all you want to do is to insert new records.

Rails Active Record - Save multiple objects at once

Each call for insertion into database will be done separately (in different transactions). But you could decrease a total delay wrapping all creations in a single transaction.

Task.transaction do
tasks.each{ |task| Task.create(...) }
end

In this case all your creations will be wrapped in one atomic db transaction.

Take a look at transaction documentation.

Also you could try accepts_nested_attributes_for.

Nested attributes allow you to save attributes on associated records through the parent.

Hope it helps.

How to save multiple records at once into a database

You have tagged the question with Ruby on Rails so I assumed you are using ActiveRecord. So,build an api for batch inserting as follows.

You angular code should look like the following

var actors = [];
angular.forEach($scope.movieCredits.credits.cast, function(item){
actors.push({
name: item.name,
character: item.character,
movie_id: movieRecordID[0].id,
});
});
createActor.create(actors);

And in your rails controller

def create
actors = Actor.create(params[:actors])
..
render json: actors
end

This is how active records handles inserting multiple records since the create methods takes an array too as follows

Model.create([{name: "John Doe", character: "The Hobbit", movie_id: 1}, {name: "Christian Bale", character: "Batman", movie_id: 2}])

This will execute ONE SQL query for N records instead of N SQL queries for N records.

Rails save multiple records from hash

Don't know if that counts as a single action, but you can iterate through the hash like this:

@consolidated_rawdata.each {|name, items_sold| Report.create(user: 
name, items_sold: items_sold)}

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

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



Related Topics



Leave a reply



Submit