4

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?

Jigar Bhatt
  • 4,217
  • 2
  • 34
  • 42
  • 1
    Please provide more information. What have you tried? What is the error? What are the databases? How are they configured? How is activerecord setup? Generally a rails console will have connections to all databases and activerecord will connect to the one they're configured to... so you don't need to do anything. – melcher Sep 01 '21 at 22:43

2 Answers2

1

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
mechnicov
  • 12,025
  • 4
  • 33
  • 56
1

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
Smek
  • 1,158
  • 11
  • 33