I need to use different database connections in different Rails models. Is there a not-so-hacky way to do that?
Any links or search keywords would be great :)
I need to use different database connections in different Rails models. Is there a not-so-hacky way to do that?
Any links or search keywords would be great :)
Add new sections to your database.yml e.g.
other_development:
adapter: mysql
database: otherdb_development
username: root
password:
host: localhost
other_production:
adapter: mysql
database: otherdb_production
username: root
password:
host: localhost
Add a class in lib/other_database.rb
class OtherDatabase < ActiveRecord::Base
establish_connection "other_#{RAILS_ENV}"
end
and then for each model which isn't in the default database subclass from OtherDatabase e.g.:
class MyModel < OtherDatabase
# my model code...
end
mikej is right. I did however write a gem that makes the model code to connect a little bit cleaner, check it out.
Rails 6 added native support for multiple databases: https://edgeguides.rubyonrails.org/active_record_multiple_databases.html
database.yml
development:
one:
<<: *default
other:
<<: *default
Model base classes:
class OneModelBase < ActiveRecord::Base
around_action :set_db
private
def set_db
ActiveRecord::Base.connected_to(database: :one) do
yield
end
end
end
class OtherModelBase < ActiveRecord::Base
around_action :set_db
private
def set_db
ActiveRecord::Base.connected_to(database: :other) do
yield
end
end
end
You'll also have different migrations and schemas per DB. Running a command like rails db:create will create all databases. You can scope commands, e.g. rails db:create:other.
In rails 4.1+ establish_connection now takes a symbol:
class OtherDbModel < ActiveRecord::Base
establish_connection :"other_#{Rails.env}"
end