i have multiple databases in my project and i want to open rails console to access both databases.
currently i can fetch data of only one default database.
In other word, how to open specific database console?
i have multiple databases in my project and i want to open rails console to access both databases.
currently i can fetch data of only one default database.
In other word, how to open specific database console?
In other word, how to open specific database console?
From official guide:
bin/rails dbconsole
figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL (including MariaDB), PostgreSQL, and SQLite3.You can also use the alias "db" to invoke the dbconsole:
bin/rails db
.If you are using multiple databases,
bin/rails dbconsole
will connect to the primary database by default. You can specify which database to connect to using--database
or--db
:bin/rails dbconsole --database=animals
So command is
rails db --db=db_name_from_database_yml
For example you have in your database.yml
production:
my_primary:
adapter: postgresql
database: some_db_name
In this case your command will be
bundle exec rails db --db=my_primary -e=production
Why don't you have a read through the documentation https://guides.rubyonrails.org/active_record_multiple_databases.html. You should be able to find just what you need. connects_to does the trick of database switching automatically of manually.
Or https://api.rubyonrails.org/classes/ActiveRecord/ConnectionHandling.html#method-i-connected_to
ActiveRecord::Base.connected_to(database: :mydb) do
# Do something here...
end