Last Updated: February 25, 2016
·
779
· shairontoledo

Simple postgresql sql to generate models from a legacy database

SELECT 'rails generate scaffold '|| initcap(table_name) || ' ' || 
(select array_to_string(array(
    SELECT column_name || ':' || case 
        when data_type='timestamp without time zone' then 'timestamp' 
        when data_type='character varying'then 'string' 
        else data_type end 
    FROM information_schema.columns 
    WHERE table_schema = 'public' and table_name = table_name order by column_name ), ' ') ) 
    FROM information_schema.tables WHERE table_schema='public'  

Above query will fetch all tables from the public schema and generate a model per line, something like:

rails generate scaffold Documents name:string size:integer uploaded_at:timestamp ....
rails generate scaffold Users username:string email:string ....