Ravi Nayak
Ravi Nayak

Reputation: 41

Establish connection does not work with Ruby console

I have configured database.yml to include "logging_development" as a label for signifying another database. One of the models is using "establish_connection" to connect to the database using this "label".

My model looks like this:

class AdHistory < ActiveRecord::Base

establish_connection "logging_#{RAILS_ENV}"

The Rails server works fine when it starts and establishes connection of the model with the concerned database. But when I start ruby console and try to use the model, it uses "development" label in database.yml to establish connections. I have looked into the issue but unable to find a solution. Here is a sample of the database.yml file:

development:
  adapter: mysql
  encoding: utf8
  reconnect: true
  database: ad_production
  pool: 5
  username: root
  password: ********
  socket: /tmp/mysql.sock

logging_development:
  adapter: mysql
  encoding: utf8
  reconnect: true
  database: ad_logging
  pool: 5
  username: root
  password: ********
  socket: /tmp/mysql.sock

I am using Ruby 1.8.7 and Rails 2.3.8

Upvotes: 2

Views: 789

Answers (2)

Ravi Nayak
Ravi Nayak

Reputation: 41

I found the answer to my question. The problem was that I was using Multi_DB gem which was intercepting all the SQL Queries that were being executed and re-directing those queries to the slave database. That was why those queries were not being executed against the database I had chosen in the "database.yml". Once the multi_db connection is nullified, the console behaves as expected. One of the problems of using "multi_db" gem is that it only accepts names of connections as "_slave_database_". So, any deviation from the expected name for multi_db gem in database.yml file will lead to errors, and the queries will not get executed against the selected database.

Upvotes: 1

Ricardo Valeriano
Ricardo Valeriano

Reputation: 7793

Have you used the RAILS_ENV=logging_development when running the rails console? If not you should, because the default Rails environment is development. So, try to load the console using this to set the RAILS_ENV variable:

RAILS_ENV=logging_development scripts/rails console

Upvotes: 1

Related Questions