Multiple database in rails
In normal rails application contain one database,but if we want rails application having more than one database that is multiple data base.
we can achieve this using multiple way.one of the way is i am showing here.it’s just 3 steps.
Lets take an e.g Project has many milestone and milestone has many task
In normal scenario model looks like following way
class Project < ActiveRecord::Base
has_many :milestones
end
class Milestone < ActiveRecord::Base
has_many :tasks
belongs_to :project
end
class Task < ActiveRecord::Base
belongs_to :milestone
end
Now we want that milestone is stored on milestone_db database and task on task_db database
Now to achieve this we have to do the following steps
1 Edit Database.yml
milestone_dev:
reconnect: false
encoding: utf8
username: <user_name>
adapter: mysql
database: milestone_db
pool: 5
password: <password>
task_dev:
reconnect: false
encoding: utf8
username: <user_name>
adapter: mysql
database: task_db
pool: 5
password: <password>
2 Edit milestone.rb and task.rb
class Milestone < ActiveRecord::Base
#add this line to use milestone_db
self.establish_connection :milestone_dev
has_many :tasks
belongs_to :project
end
class Task < ActiveRecord::Base
#add this line to use task_db
set_table_name "tasks"
belongs_to :milestone
end
3 After editing model edit migration file
class CreateMilestones < ActiveRecord::Migration
def self.connection
Milestone.connection
end
.....
end
Now rails application is ready with multiple database.