Pragmatic Development Notes

Software development related stuff

RMRE - rails models reverse engineering gem

Very often I have to work on databases which do not follow ActiveRecord convention and making ActiveRecord models, if number of tables is large, is very slow and boring task. In order to speed up and simplify it I’ve created Rmre gem. Gem is quite simple yet you might find it useful if you want to create fixtures, migrations or simply port application to Ruby on Rails.

So how it works? For each table in the database, gem creates model. Name of the model is created using Rails classify method. Moreover, if table’s primary key is not column named “id” gem sets primary key by adding set_primary_key "primaryKeyColumnName" line to the model. In addition for MySQL, PostgreSQL, Oracle or MS SQL foreign keys are analyzed and for each constraint gem generates belongs_to or has_many lines. Here is model created for table store in Sakila MySQL test database:

1
2
3
4
5
6
7
8
9
class Store < ActiveRecord::Base
  set_primary_key :store_id
  set_table_name 'store'
  has_many :customers, :class_name => 'Customer'
  has_many :inventories, :class_name => 'Inventory'
  has_many :staffs, :class_name => 'Staff'
  belongs_to :address, :class_name => 'Addres', :foreign_key => :address_id
  belongs_to :staff, :class_name => 'Staff', :foreign_key => :manager_staff_id
end
  1. Wilson says:

    I tried to use this gem, inside my application dir, but when I typed:

    rmre -a postgresql -d Pessoa -u postgres -p <I_put_my_pass_here> -o /app/models

    I got the error:

    ... generator.rb:29:in 'create models':undefined method 'exists?' for Dir:Class (NoMethodError)

    Can you help me?

  2. Bosko Ivanisevic says:

    Can you tell me which Ruby do you use, which OS? Rmre works with ActiveRecord 3.0 version thus with Ruby 1.9. Have you tried it with Ruby 1.8.x maybe?

  3. Martin says:

    Any example for Oracle database?

  4. Boško Ivanišević says:

    What example do you mean exactly? Gem is working on Oracle just same as it works on any database that is supported by ActiveRecord. Particularly, for Oracle you need oci8 and oracle_enhanced gems. Configuration depends on your Oracle installation and should look similar to this:

    adapter: oracle_enhanced
    database: localhost/xe
    username: <your_username>
    password: <your_password>

  5. Bobby Dolkov says:

    Hi How do you use this when reverse engineering tables in a schema within a database? Thanks!

  6. Boško Ivanišević says:

    I'm not sure what exactly you want to achieve but if you want to dump database schema use --dump-schema option. This will create script to easily re-create database (only structure, not data).

Post a comment


(lesstile enabled - surround code blocks with ---)