jesjos / active_record_upsert

Upsert for Rails 5 / Active Record 5
MIT License
207 stars 51 forks source link

Custom `upsert_keys` per call to `upsert` #74

Closed dounan closed 4 years ago

dounan commented 6 years ago

We have a foo table that has two unique indices:

t.index ["a", "b", "c"], unique: true, using: :btree
t.index ["a", "b"], unique: true, where: "(c IS NULL)", using: :btree

In our model, we specify the upsert_keys to cover the first unique index as follows:

class Foo < ActiveRecord::Base
  upsert_keys [:a, :b, :c]
end

However, whenever we do an upsert on a record that has a nil value for c, we run into duplicate key errors from the second unique index.

Is there any way in the current library to set the index_column_names and index_expression per upsert call?

For example, something like:

if foo.c.nil?
  foo.upsert(upsert_keys: [:a, :b], :upsert_options: {where: "c IS NULL"})
else
  foo.upsert(upsert_keys: [:a, :b, :c])
end
hahuang65 commented 5 years ago

Would like to bump this, as I'm requiring this feature for something I'm working on as well.

It's not uncommon to have different upsert clauses.

olleolleolle commented 5 years ago

Pull Requests are welcome!

hahuang65 commented 5 years ago

@olleolleolle just added one 👍