Here is a question comes up a lot. Here is how to do it without additional plugin.
config/database.yml:
development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000second_development:
adapter: sqlite3
database: db/second_development.sqlite3
timeout: 5000test:
adapter: sqlite3
database: db/test.sqlite3
timeout: 5000second_test:
adapter: sqlite3
database: db/second_test.sqlite3
timeout: 5000production:
adapter: sqlite3
database: db/production.sqlite3
timeout: 5000second_production:
adapter: sqlite3
database: db/second_production.sqlite3
timeout: 5000
migration for models in first database is like normal migration, example (xxxxxxx_create_user.rb):
def self.up
create_table “users” do |t|
t.string “password”
t.string “email”t.timestamps
end
end
def self.down
drop_table :users
end
migration for models in second database require slightly modification, example (xxxxxxx_create_dogs.rb)
def self.up
ActiveRecord::Base.establish_connection “second_#{RAILS_ENV}”
create_table :dogs do |t|
t.string :name, :null=>falset.timestamps
end
ActiveRecord::Base.establish_connection “#{RAILS_ENV}”end
def self.down
ActiveRecord::Base.establish_connection “second_#{RAILS_ENV}”
drop_table :users
ActiveRecord::Base.establish_connection “#{RAILS_ENV}”end
Note that schema_migration table is located in the first database (default one) only in this case.
Models for the first (default database) is the same as regular rails model.
Models for the second database requires adding the following line in the Models:
establish_connection “second_#{RAILS_ENV}”
Example:
class Dog < ActiveRecord::Base
establish_connection “second_#{RAILS_ENV}”
end
That is it. Not that complicated.