Jerod Santo changelog.com/posts

Use Rails with the db schema you always wanted

reactive_record from Chris 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 or check out the source on GitHub.


Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00