Support Multiple Databases with Ruby on Rails
- Add a new DB configuration
my_app_development:
adapter: mysql2
encoding: utf8
reconnect: false
database: my_app_development
pool: 5
username: root
password: my_secret
socket: /tmp/mysql.sock
- Add the test DB my_app_test and production DB my_app_production configuration similar as above
- 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
- Create a new model (Member)
% rails generate model Member ...
- Run the migration code to create the new DB table
- Create a new model class for the legacy DB table (groups)
class Group < ActiveRecord::Base
has_many :members
end
- 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
- 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
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
|