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.
The upsert gem seems to do just that - I found it while googling to see if "upsert" is a thing.
How about this:
class Category < ActiveRecord::Base
...
class << self
def upsert(name)
transaction { self.find_or_create_by(name: name).id }
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With