views:

120

answers:

2

Hi there,

I have a Model (MessageImporter) that connects to a different Database than the other models using self.establish_connection. Everything works fine when I pass the connection info hardcoded. Now I need the connection to depend on the current environment. So I added the info to my application_config.yml (it's a simple nifty_config). I got stuck at how to pass the connection info to self.establish_connection.

Here's my current code:

class MessageImporter < ActiveRecord::Base
  self.establish_connection lambda {{
    :adapter => APP_CONFIG[:external_messages][:adapter],
    :host => APP_CONFIG[:external_messages][:host],
    :database => APP_CONFIG[:external_messages][:database],
    :username => APP_CONFIG[:external_messages][:username],
    :password => APP_CONFIG[:external_messages][:password]
  }}

# […]

I get an undefined method 'symbolize_keys' for #<Proc:0x2564224>-. Error I also tried it without the lambda, but that does not work either and I get an even weirder error:

Please install the  adapter: `gem install activerecord--adapter` (no such file to load -- active_record/connection_adapters/_adapter)

Or is there a better/Rails-ish way to set a different db-connection for individual models?

A: 
John Topley
Jup, i tried it. But with that code i even get Syntax-Errors: http://pastie.org/768685
Nils Riedemann
What happens if you replace the symbols in the hash with strings, so `:adapter => APP_CONFIG['external_messages']['adapter']` etc?
John Topley
That gives me an `You have a nil object when you didn't expect it!`-Error. Found a solution will post it in a sec.
Nils Riedemann
+2  A: 

Little different approach and it works:

Adding the connection info to the regular database.yml:

development:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: […]
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

  message_import:
    adapter: mysql
    encoding: utf8
    username: […]
    password: […]
    database: […]
    host: […]

Note the nesting! message_import ist nested beneath development.

Within the message_importer.rb:

class MessageImporter < ActiveRecord::Base
  establish_connection configurations[RAILS_ENV]['message_import'] 

Still wondering why my first approach didn't work but this does just as expected.

Nils Riedemann