Skip to content

Commit

Permalink
Consistent insert_all interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
berniechiu committed Jun 29, 2022
1 parent c3c7475 commit 56e66a0
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
18 changes: 18 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
* `ActiveRecord::Persistence::ClassMethods#insert_all!` now supports `unique_by` option.

```ruby
books = [
{ name: 'A', author_id: 1, price: 100 },
{ name: 'B', author_id: 1, price: 200 },
{ name: 'A', author_id: 1, price: 300 },
]

# Raises ActiveRecord::RecordNotUnique
Book.insert_all!(books, unique_by: [:name, :author_id])

# Returns ActiveRecord::Result
Book.insert_all(books, unique_by: [:name, :author_id])
```

*Bernie Chiu*

* Update `db:prepare` task to load schema when an uninitialized database exists, and dump schema after migrations.

*Ben Sheldon*
Expand Down
4 changes: 2 additions & 2 deletions activerecord/lib/active_record/persistence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,8 @@ def insert!(attributes, returning: nil, record_timestamps: nil)
# { id: 1, title: "Rework", author: "David" },
# { id: 1, title: "Eloquent Ruby", author: "Russ" }
# ])
def insert_all!(attributes, returning: nil, record_timestamps: nil)
InsertAll.new(self, attributes, on_duplicate: :raise, returning: returning, record_timestamps: record_timestamps).execute
def insert_all!(attributes, returning: nil, unique_by: nil, record_timestamps: nil)
InsertAll.new(self, attributes, on_duplicate: :raise, returning: returning, unique_by: unique_by, record_timestamps: record_timestamps).execute
end

# Updates or inserts (upserts) a single record into the database in a
Expand Down
10 changes: 10 additions & 0 deletions activerecord/test/cases/insert_all_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,16 @@ def test_insert_all_raises_on_duplicate_records
end
end

def test_insert_all_raises_on_duplicate_records_when_unqiue_by_is_provided
assert_raise ActiveRecord::RecordNotUnique do
Cart.insert_all! [
{ id: 1, shop_id: 1, title: "My cart" },
{ id: 2, shop_id: 1, title: "My another cart" },
{ id: 1, shop_id: 1, title: "My another cart" },
], unique_by: [:shop_id, :id]
end
end

def test_insert_all_returns_ActiveRecord_Result
result = Book.insert_all! [{ name: "Rework", author_id: 1 }]
assert_kind_of ActiveRecord::Result, result
Expand Down

0 comments on commit 56e66a0

Please sign in to comment.