Skip to content

Instantly share code, notes, and snippets.

@MarioCarrion
Created July 19, 2015 03:01
Show Gist options
  • Save MarioCarrion/5829515f1fc4caf685b4 to your computer and use it in GitHub Desktop.
Save MarioCarrion/5829515f1fc4caf685b4 to your computer and use it in GitHub Desktop.
Dynamically create ActiveRecord models (PostgreSQL example)
# How to dynamically create model classes in PostgreSQL and ActiveRecord?
require 'active_record'
class ModelFactory < ActiveRecord::Base
self.abstract_class = true
class << self
def build_model(params)
schema = params[:schema]
table = params[:table]
full_name = "#{schema}.#{table}"
create_database_objects(schema, table, full_name)
model = Class.new(ModelFactory) do
self.table_name = full_name
end
model
end
private
def create_database_objects(schema, table, full_name)
connection = ModelFactory.connection
# Create Schema
unless connection.schema_exists?(schema)
begin
connection.create_schema(schema)
rescue PG::DuplicateSchema
end
end
# Create Table
new_table = false
unless connection.table_exists?(full_name)
new_table = true
begin
connection.create_table(model.table_name) do |table|
table.column :name, :string, limit: 50, null: false
table.column :address, :string, limit: 300, null: false
table.column :timestamp, :integer, null: false
end
rescue PG::DuplicateTable
end
end
# What's next? Maybe adding indexes, who knows, sky is the limit
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment