Skip to content

Commit d2de6f7

Browse files
committed
Improve README
1 parent 5de9877 commit d2de6f7

File tree

1 file changed

+42
-8
lines changed

1 file changed

+42
-8
lines changed

README.md

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,62 @@
11
# ActiveRecord::ReturningAttributes
22

3-
Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/active_record/returning_attributes`. To experiment with that code, run `bin/console` for an interactive prompt.
3+
ReturningAttributes provides a way to populate model attributes with database-backed default values or values set via database triggers when creating or updating single records without executing additional database queries.
44

5-
TODO: Delete this and the text above, and describe your gem
5+
#### Slightly Longer Description
6+
7+
When having database-backed default values (like `NOW()`) or values set via database triggers, we don't get to see them when creating or updating records in Rails. This is because when inserting records, the PostgreSQL `RETURNING` clause only states the `id` (or a different primary key) column, other columns are not returned back to Rails-land. Similar to inserts, updates don't get to see those values because there's no `RETURNING` clause involved at all.
8+
9+
Internally this library changes the `RETURNING` clause for inserts and adds it for updates so we don't have to reload records.
10+
11+
Caveats:
12+
13+
- PostgreSQL only
14+
- Only tested in Rails 5.2.0
15+
- Overrides ActiveRecord core code
616

717
## Installation
818

919
Add this line to your application's Gemfile:
1020

1121
```ruby
12-
gem 'active_record-returning_attributes'
22+
gem 'active_record-returning_attributes', github: 'tbuehlmann/active_record-returning_attributes'
1323
```
1424

1525
And then execute:
1626

17-
$ bundle
27+
```sh
28+
$ bundle install
29+
```
1830

19-
Or install it yourself as:
31+
## Usage
2032

21-
$ gem install active_record-returning_attributes
33+
Assume having a database-backed default value for the `uuid` column or a trigger that sets the value.
2234

23-
## Usage
35+
Before:
36+
37+
```ruby
38+
class Project < ApplicationRecord
39+
end
40+
41+
project = Project.create
42+
project.uuid # => nil
43+
44+
project.reload
45+
project.uuid # => '2b57df54-3768-45c6-ad10-aeec028e7735'
46+
```
47+
48+
After:
49+
50+
```ruby
51+
class Project < ApplicationRecord
52+
self.returning_attributes = [:uuid]
53+
end
54+
55+
project = Project.create
56+
project.uuid # => '2b57df54-3768-45c6-ad10-aeec028e7735'
57+
```
2458

25-
TODO: Write usage instructions here
59+
By setting `self.returning_attributes`, ActiveRecord will request those columns via the `RETURNING` clause and populate the corresponding attributes in your model.
2660

2761
## Development
2862

0 commit comments

Comments
 (0)