i am trying to connect to different databases in my script but i am getting ActiveRecord::ConnectionNotEstablished: No connection pool for 'ActiveRecord::Base' found for the 'main' shard.
relevant code from database.yml is below
test:
primary:
adapter: postgresql
database: test
database: "<%= ENV['DATABASE_NAME'] %>"
username: "<%= ENV['DATABASE_USERNAME'] %>"
password: "<%= ENV['DATABASE_PASSWORD'] %>"
host: "<%= ENV['DATABASE_HOST'] %>"
main:
adapter: postgresql
username: postgres
database: "<%= ENV['API_MAIN_DATABASE_NAME'] %>"
password: "<%= ENV['API_DATABASE_PASSWORD'] %>"
host: "<%= ENV['API_DATABASE_HOST'] %>"
database_tasks: false
prediction:
adapter: postgresql
username: postgres
database: "<%= ENV['API_PREDICTION_DATABASE_NAME'] %>"
password: "<%= ENV['API_DATABASE_PASSWORD'] %>"
host: "<%= ENV['API_DATABASE_HOST'] %>"
database_tasks: false
onshore:
adapter: postgresql
username: postgres
database: "<%= ENV['API_US_ONSHORE_DATABASE_NAME'] %>"
password: "<%= ENV['API_DATABASE_PASSWORD'] %>"
host: "<%= ENV['API_DATABASE_HOST'] %>"
database_tasks: false
i have 3 models connecting to main, prediction & onshore databases as below
class ExternalRecord < ApplicationRecord
self.abstract_class = true
connects_to shards: { writing: :primary, reading: :main }
end
class ExternalRecordPrediction < ApplicationRecord
self.abstract_class = true
connects_to shards: { writing: :primary, reading: :prediction }
end
class ExternalRecordOnshore < ApplicationRecord
self.abstract_class = true
connects_to shards: { writing: :primary, reading: :onshore }
end
I am trying to do some processing by connecting to these three different database in a loop like below
ActiveRecord::Base.connected_to(role: :reading, shard: :main) do
results = ActiveRecord::Base.connection.execute(query_here)
#process results
But i get an error ActiveRecord::ConnectionNotEstablished: No connection pool for 'ActiveRecord::Base' found for the 'main' shard.
How do i switch to different databases in the script.
I am using Rails 7
I was previously using Rails 5 and using ar-octopus to achieve this.
ActiveRecord::Baseshares a connection with yourApplicationRecordclass or some other class whereprimary_abstract_classis set. You have to set upconnects_tothere.With shards
Reference:
rails v7.0.2.3ruby v3.1.1You can also just force a connection. But I don't know how safe this is, I wouldn't use it in the main app.