Ruby on Rails 3 Model Working with Legacy Database

Support Multiple Databases with Ruby on Rails

  1. Add a new DB configuration
    config/database.yml
    my_app_development:
        adapter: mysql2
        encoding: utf8
        reconnect: false
        database: my_app_development
        pool: 5
        username: root
        password: my_secret
        socket: /tmp/mysql.sock
    
  2. Add the test DB my_app_test and production DB my_app_production configuration similar as above
  3. For the models requiring the non-default databases
    class Member < ActiveRecord::Base
       establish_connection "my_app_#{RAILS_ENV}"
    end
    

Override the DB table name in Ruby on Rails

Define a model Member to access the legacy DB table t_members

class Member < ActiveRecord::Base
  set_table_name :t_members
end

Use a legacy primary key name for a DB table in Ruby on Rails

Override the default primary key column name id with the primary key name member_id of a legacy table

class Member < ActiveRecord::Base
  set_primary_key :member_id
end

Use a non-integer for the primary key

Add a column to be used as primary key in the migration file

create_table :groups, {:id => false} do |t|
  t.string :gp_id
  ...
end
execute "ALTER TABLE groups ADD PRIMARY KEY (gp_id);"

Set the primary key name manually

class Group < ActiveRecord::Base
  set_primary_key :gp_id
  ...
end

Access to legacy DB column name

class Member < ActiveRecord::Base
 alias_attribute :name, :legacy_member_name
end
  • @member.name or @member.name = 'John' will access the DB column legacy_member_name

Associate a new DB table using Ruby on Rails with a Legacy DB table

A new DB table is referencing a legacy DB table

  1. Create a new model (Member)
    % rails generate model Member ...
    
  2. Run the migration code to create the new DB table
    rake db:migrate
    
  3. Create a new model class for the legacy DB table (groups)
    app/models/company.rb
    class Group < ActiveRecord::Base
      has_many :members
    end
    
  4. Add the association in Member
    class Member < ActiveRecord::Base
       belongs_to :group, :primary_key => :g_id
    end
    
    • Use :primary_key to define the primary key name of the legacy DB table
      • :g_id is the primary key for the legacy DB table group
  5. Access the data with the association
        @group = Member.find(params[:id]).group
    
        @members = Group.find(params[:id]).members
    

A legacy DB table is referencing another legacy DB table in Ruby on Rails

app/models/member.rb
class Member < ActiveRecord::Base
   belongs_to :group, :foreign_key => :g_fkid, :primary_key => :g_id
end
  • :g_fkid is the foreign key column name in the legacy DB table members
  • :g_id is the primary key for the legacy DB table group