Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upsert in Rails ActiveRecord

Does ActiveRecord have a built-in upsert functionality? I know I could write it myself but I obviously don't want to if such a thing already exists.

like image 847
Jason Swett Avatar asked Jan 14 '11 20:01

Jason Swett


People also ask

How does Upsert work in Rails?

Upsert in database terms refers to an operation which should insert a row into a database table if it doesn't not already exist, or update it if it does. One can implement this function in Rails by writing __anActiveRecordExtension__ . This will allow you to call the upsert method on any model.

What is upsert in Ruby?

Updates or inserts (upserts) a single record into the database in a single SQL INSERT statement. It does not instantiate any models nor does it trigger Active Record callbacks or validations. Though passed values go through Active Record's type casting and serialization.

What Upsert means?

The term upsert is a portmanteau – a combination of the words “update” and “insert.” In the context of relational databases, an upsert is a database operation that will update an existing row if a specified value already exists in a table, and insert a new row if the specified value doesn't already exist.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.


1 Answers

There is an awesome new feature in rails 6: they added upsert and upsert_all to ActiveRecord

More info can be found here https://edgeapi.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-upsert_all

like image 161
Chris Avatar answered Sep 26 '22 13:09

Chris