https://github.com/hauntedhost/enum_from_pg_constraint
Derive a Rails from an existing PostgreSQL constraint
https://github.com/hauntedhost/enum_from_pg_constraint
Last synced: 8 months ago
JSON representation
Derive a Rails from an existing PostgreSQL constraint
- Host: GitHub
- URL: https://github.com/hauntedhost/enum_from_pg_constraint
- Owner: hauntedhost
- License: mit
- Created: 2016-02-01T02:04:03.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2016-02-03T15:48:10.000Z (over 10 years ago)
- Last Synced: 2025-09-22T21:47:11.923Z (9 months ago)
- Language: Ruby
- Homepage:
- Size: 8.79 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
## EnumFromPgConstraint
Derive a Rails [enum](http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html) from an existing PostgreSQL constraint.
## Usage:
Given a migration to create table `Thing` with a PostgreSQL constraint:
```ruby
class CreateThing < ActiveRecord::Migration
def up
create_table :things do |t|
t.string :name
t.string :status, null: false, default: 'pending'
t.timestamps null: false
end
execute <<-SQL.strip_heredoc
ALTER TABLE things
ADD CONSTRAINT allowed_statuses
CHECK (status IN (
'pending', -- thing not yet attempted
'success', -- thing succeeded
'failure' -- thing failed
));
SQL
end
def down
drop_table :things
end
end
```
Add the constraint to your Model:
```ruby
class Thing < ActiveRecord::Base
include EnumFromPgConstraint
enum_from_pg_constraint :status
end
```
```ruby
$ rails c
> Thing.statuses
=> {"pending"=>"pending", "success"=>"success", "failure"=>"failure"}
> Thing.create(name: 'Hello World!')
> Thing.pending
=> [#]
```
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/somlor/enum_from_pg_constraint. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).