Topic: Scaffolding an existing Database with Rails 2.0

So you've started learning Rails 2.0 with all the CRUD,DRY and REST stuff.
You've completed the introductory Rails 2 tutorial.

Now you're ready to try this out on your own project, with an existing database full of data.
Unfortunately, all the tutorials instruct how to create a DB from scratch using migrations.


I've found two solutions.


One is to create a new, empty db from scratch using RAILS migrations. Then transfer your existing records to it. Just follow the tutorials and change the db/table/column names as necessary.
Then dump the data into your new DB. And see it appear in your Rails app.



The other is to try to integrate the existing DB into rails.
This requires knowing much more about the working of rails than presented in tutorials.

Re: Scaffolding an existing Database with Rails 2.0

The first thing a novice should know about rails
is that it wants almost unfettered access to the database.

If your existing database has existing users & permissions, you'll probably try to use one of them and run into trouble.

The first time you run migrations, Rails will create (behind your back) a table in the Database named schema_info. If your username in config/database.yml does not have the ability to create new tables you're going to get error messages.


See post http://railsforum.com/viewtopic.php?id=16272
as I try to figure out all the permissions on the Database a Rails app will need.


So far as I can tell, a typical Rails application will access the Database with a user that is a copy of root. And therefore has ALL PERMISSIONS enabled on it's Database.

Why a Rails app needs grant permissions is still a mystery to me.

Re: Scaffolding an existing Database with Rails 2.0

For my app I just wrote a simple rake task like the following:

desc "Build scaffolds from existing db"
task :useExistingDB => :environment do
  connection = ActiveRecord::Base.connection
  connection.tables.each do |table|
    begin

      command = "#{RAILS_ROOT}/script/generate"
      args = ["scaffold ","#{table} s"]
      columns = ActiveRecord::Base.connection.columns(table)
      columns.each do |col|
          args << "#{col.name}:#{col.type} "
     end
     puts "#{command} #{args.to_s}"
      system("#{command} #{args.to_s}")
      puts "generated '#{table}'"
    rescue
      puts "failed: #{$!}"
    end
  end
end

Last edited by justdewit (2009-04-01 17:49:03)

Re: Scaffolding an existing Database with Rails 2.0

You can also use this script : http://github.com/ahe/reverse_scaffold

Re: Scaffolding an existing Database with Rails 2.0

Yet another way is to use

rake db:structure:dump