Awesome
SchemaPlus::DbDefault
SchemaPlus::DbDefault provides a constant ActiveRecord::DB_DEFAULT
that you can use to set an attribute's database column to the default value or expression specified in the database schema.
(Without ActiveRecord::DB_DEFAULT
you can update a column to NULL
but not to its default value.)
SchemaPlus::DbDefault is part of the SchemaPlus family of Ruby on Rails ActiveRecord extension gems.
Usage
Use ActiveRecord::DB_DEFAULT
as a "magic value" for attributes; when saved it will cause SQL to use the DB default value.
record.update_attributes(category: ActiveRecord::DB_DEFAULT) # SQL: UPDATE tablename SET category = DEFAULT
record.reload
After the save, you'll need to reload the record to replace ActiveRecord::DB_DEFAULT
with the value assigned by the database.
Installation
<!-- SCHEMA_DEV: TEMPLATE INSTALLATION - begin --> <!-- These lines are auto-inserted from a schema_dev template -->As usual:
gem "schema_plus_db_default" # in a Gemfile
gem.add_dependency "schema_plus_db_default" # in a .gemspec
<!-- SCHEMA_DEV: TEMPLATE INSTALLATION - end -->
Compatibility
SchemaPlus::DbDefault is tested on:
<!-- SCHEMA_DEV: MATRIX - begin --> <!-- These lines are auto-generated by schema_dev based on schema_dev.yml -->- ruby 2.1.5 with activerecord 4.2, using mysql2 and postgresql
Sqlite3 does not support setting a column to its default value. Attempting to use ActiveRecord::DB_DEFAULT
will raise ActiveRecord::StatementInvalid
History
- 0.1.1 - Upgrade schema_plus_core dependency
- 0.1.0 - Initial release extracted from schema_plus 1.x
Development & Testing
Are you interested in contributing to SchemaPlus::DbDefault? Thanks! Please follow the standard protocol: fork, feature branch, develop, push, and issue pull request.
Some things to know about to help you develop and test:
<!-- SCHEMA_DEV: TEMPLATE USES SCHEMA_DEV - begin --> <!-- These lines are auto-inserted from a schema_dev template -->-
schema_dev: SchemaPlus::DbDefault uses schema_dev to facilitate running rspec tests on the matrix of ruby, activerecord, and database versions that the gem supports, both locally and on travis-ci
To to run rspec locally on the full matrix, do:
$ schema_dev bundle install $ schema_dev rspec
You can also run on just one configuration at a time; For info, see
schema_dev --help
or the schema_dev README.The matrix of configurations is specified in
schema_dev.yml
in the project root.
- schema_plus_core: SchemaPlus::DbDefault uses the SchemaPlus::Core API that provides middleware callback stacks to make it easy to extend ActiveRecord's behavior. If that API is missing something you need for your contribution, please head over to schema_plus_core and open an issue or pull request.
- schema_monkey: SchemaPlus::DbDefault is implemented as a schema_monkey client, using schema_monkey's convention-based protocols for extending ActiveRecord and using middleware stacks.