Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement `upsert` for PostgreSQL in ActiveRecord?

I have a stream of data, which contains categories. I want to maintain a Category table which should contain every category I encounter exactly once.

I want to implement a id = Category.upsert(name), which should be atomic (of course), and - if possible - not use stored procedures on the DB side.

like image 631
Uri Agassi Avatar asked Feb 08 '26 01:02

Uri Agassi


2 Answers

The upsert gem seems to do just that - I found it while googling to see if "upsert" is a thing.

like image 171
Leonid Shevtsov Avatar answered Feb 12 '26 06:02

Leonid Shevtsov


How about this:

class Category < ActiveRecord::Base
  ...

  class << self
    def upsert(name)
      transaction { self.find_or_create_by(name: name).id }
    end
  end
end
like image 38
lacrosse Avatar answered Feb 12 '26 06:02

lacrosse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!