A short story and a problem, how you develop an application if it needs to use an already existing database structure? Rails generates models,controllers and does scaffolding with close to no effort but what if you have your on ideas about database structure? And without Rails you need something to make Ruby work on the web. Let’s find answers.
The story a bit longer:
Recently I have been working on a PHP application which was handling registrations for an event. Beside the online registration there was also offline registration and a software took care of it which was developed in C# by my friend. The point is that here the database structure was set, fix and we needed to stick to that. PHP could handle this situation quite easily. I set up models according to the database structure and dealt with them through the models. All was a breeze even though it was my first “real” PHP application. I’m very happy for it actually however probably it’s not the nicest code. You can check it out on github.
So now I have been asked by my freind to create a tiny little app which queries a vast database and reads out the status of orders to display them to his clients. Seems to be a simple task in PHP but what about Ruby? This is the question I would like to answer. (the database has many tables and columns and can not be modified).
There’s kind of a way. Create a new Rails 2.2 app (it can’t be 2.3 or 3.0, the gem hasn’t been updated since 2007). Then install and use the Magic Model Generator gem.
This will look at your existing database and extra all the models from it, like magic. Since the structure of basic ActiveRecord model files is pretty similar in Rails 3, you can just copy them into your current project and tweak as necessary.
I wouldn’t say that this solution is convincing for me, I should be able to do that without a gem and not only with Rails 2.2 so I went on looking for the right one.
Then I found a rather interesting slideshow from 2009 which seemed quite useful and might could work.
Still there is the question how to reverse engineer the models and controllers for Rails. I will give this a try and update the post later. Until that if you know something about how to integrate legacy databases to Rails projects please share it with us in the comments.