Search code examples
ruby-on-rails-3postgresqldatabase-connectionmultiple-databases

Cannot connect to two postgres databases in rails 3.2.


I've tried a few methods found on stack overflow for connecting to two database in rails two however non of them are working. Here's what I've got at the moment:

In the database.yml there's two connection settings:

development:
  adapter: postgresql
  host: localhost
  database: blerg
  username: postgres
  encoding: utf8

production:
  blah...

test: &test
  blah...

cucumber:
  <<: *test

static_api_development:
  adapter: postgresql
  host: localhost
  database: blerg-static-api
  username: postgres
  encoding: utf8

static_api_production:
  blah...

static_api_test:
  blah...

And then I have lots of normal models in the rails app, but also the odd special model that need to connect to the other database, here's how I've set it up...

There is a module in the models folder called static_table.rb which has this content:

class StaticTable < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "static_api_#{Rails.env}"
end

Then the special models that need the other tables have this:

class ContentItem < StaticTable
  self.table_name = 'content_items'
end

However if you call ContentItem.all in a controller it says the 'content_items' table does not exist and the database connection is showing as 'blerg' not the 'blerg-static-api' which it should be.

Any help would be much appreciated thanks.


Solution

  • Try to establish_connection in ContentItem too.