Skip to content

Commit

Permalink
Add unique_by support to upsert
Browse files Browse the repository at this point in the history
  • Loading branch information
kaspth committed Jan 14, 2024
1 parent bc60ec4 commit 604a8f1
Show file tree
Hide file tree
Showing 4 changed files with 6 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/oaken/stored/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ def create(label = nil, **attributes)
record
end

def upsert(label = nil, **attributes)
def upsert(label = nil, unique_by: nil, **attributes)
attributes = @attributes.merge(attributes)
attributes.transform_values! { _1.respond_to?(:call) ? _1.call : _1 }

type.new(attributes).validate!
record = type.new(id: type.upsert(attributes, returning: :id).rows.first.first)
record = type.new(id: type.upsert(attributes, unique_by: unique_by, returning: :id).rows.first.first)
label label => record if label
record
end
Expand Down
2 changes: 2 additions & 0 deletions test/dummy/db/migrate/20231017160024_create_plans.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ def change
t.integer :price_cents, null: false

t.timestamps

t.index :title, unique: true, name: "uniqueness"
end
end
end
1 change: 1 addition & 0 deletions test/dummy/db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
t.integer "price_cents", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["title"], name: "uniqueness", unique: true
end

create_table "users", force: :cascade do |t|
Expand Down
1 change: 1 addition & 0 deletions test/dummy/db/seeds.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def users.create_labelled(label, **) = create(label, **)

section :stems
section :leafs
def plans.upsert(*, unique_by: :title, **) = super

section do
seed :accounts, :data
Expand Down

0 comments on commit 604a8f1

Please sign in to comment.