The Changelog

Open Source moves fast. Keep up.

Use Rails with the db schema you always wanted

[reactive_record][] from [Chris Wilson][wilson] is a nifty library that generates ActiveRecord models to fit a pre-existing [PostgreSQL][] database.

You just use typical [DDL][] to define your PostgreSQL tables, run the `reactive_record` generator, and voilĂ : it will create a model file for each of your tables, define validations using key/uniqueness/presence constraints, and even set up your associations for you.

Here’s an example `employees` table from the README:

class CreateEmployees < ActiveRecord::Migration
def up
execute <<-SQL
CREATE TABLE employees (
id SERIAL,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
start_date DATE NOT NULL,

PRIMARY KEY (id),
CONSTRAINT company_email CHECK (email LIKE ‘%@example.com’)
);
SQL
end

def down
drop_table :employees
end
end

And the generated model:

class Employees < ActiveRecord::Base
set_table_name ‘employees’
set_primary_key :id
validate :id, :name, :email, :start_date, presence: true
validate :email, uniqueness: true
validate { errors.add(:email, “Expected TODO”) unless email =~ /.*@example.com/ }
end

Pretty cool. As Chris says, it’s *your* convention over configuration. Get [the gem][reactive_record_gem] or check out [the source][reactive_record] on GitHub.

[reactive_record]:https://github.com/twopoint718/reactive_record
[reactive_record_gem]:https://rubygems.org/gems/reactive_record
[DDL]:http://en.wikipedia.org/wiki/Data_definition_language
[wilson]:http://sencjw.com/
[PostgreSQL]:http://postgresql.org


Have comments? Send a tweet to @TheChangelog on Twitter.

Subscribe to The Changelog Weekly – our weekly email covering everything that hits our open source radar.