Different DB connection for individual model depending on environment
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[:externa开发者_如何学JAVAl_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?
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.
According to the documentation, the establish_connection
method accepts a hash as input. Did you try this?—
class MessageImporter < ActiveRecord::Base
establish_connection {
: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]
}
精彩评论