Home

Awesome

Gem Version Build Status Coverage Status

SchemaPlus::DefaultExpr

SchemaPlus::DefaultExpr extends ActiveRecord's migrations to allow you to set the default value of a column to an SQL expression.

This gem works with PostgreSQL and Sqlite3, but not MySQL; see Compatibilitybelow.

SchemaPlus::DefaultExpr is part of the SchemaPlus family of Ruby on Rails ActiveRecord extension gems.

Installation

<!-- SCHEMA_DEV: TEMPLATE INSTALLATION - begin --> <!-- These lines are auto-inserted from a schema_dev template -->

As usual:

gem "schema_plus_default_expr"                # in a Gemfile
gem.add_dependency "schema_plus_default_expr" # in a .gemspec
<!-- SCHEMA_DEV: TEMPLATE INSTALLATION - end -->

<a name="compatibility"></a>Compatibility

SchemaPlus::DefaultExpr is tested on:

<!-- SCHEMA_DEV: MATRIX - begin --> <!-- These lines are auto-generated by schema_dev based on schema_dev.yml --> <!-- SCHEMA_DEV: MATRIX - end -->

MySQL only supports SQL expression defaults for TIMESTAMP column types, which ActiveRecord does not use. So SchemaPlus::DefaultExpr does not work with MySQL.

Usage

SchemaPlus::DefaultExpr augments the syntax for setting column defaults, to support expressions or constant values:

t.datetime :seen_at, default: { expr: 'NOW()' }
t.datetime :seen_at, default: { value: "2011-12-11 00:00:00" }

The standard syntax will still work as usual:

t.datetime :seen_at, default: "2011-12-11 00:00:00"

Also, as a convenience

t.datetime :seen_at, default: :now

resolves to:

NOW()                 # PostgreSQL
(DATETIME('now'))     # SQLite3
invalid               # MySQL

Note on PostgreSQL & json:

If you are using Postgresql with a json column, ActiveRecord allows you to use a Hash for a default value. Be aware that if the hash contains just one key which is :expr or :value, then SchemaPlus::DefaultExpr will interpret, and use the corresponding value for the default. That is, these are equivalent:

t.json :fields, default: { value: { field1: 'a', field2: 'b' } }
t.json :fields, default: { field1: 'a', field2: 'b' }

History

Development & Testing

Are you interested in contributing to SchemaPlus::DefaultExpr? 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: TEMPLATE USES SCHEMA_DEV - end --> <!-- SCHEMA_DEV: TEMPLATE USES SCHEMA_PLUS_CORE - begin --> <!-- These lines are auto-inserted from a schema_dev template --> <!-- SCHEMA_DEV: TEMPLATE USES SCHEMA_PLUS_CORE - end --> <!-- SCHEMA_DEV: TEMPLATE USES SCHEMA_MONKEY - begin --> <!-- These lines are auto-inserted from a schema_dev template --> <!-- SCHEMA_DEV: TEMPLATE USES SCHEMA_MONKEY - end -->