我正在尝试设置 Rails (v3.2.2) 以使用多个数据库。我是基于这个Connecting Rails 3.1 with Multiple Databases做的。
我的模型:
class Category < ActiveRecord::Base
establish_connection :category_database
self.primary_key = "cat_id"
validates_presence_of :name, :display_name, :description, :icon, :image, :parent_category_id, :create_time
end
数据库.yml:
category_database:
adapter: mysql2
encoding: utf8
reconnect: false
database: main_cat
pool: 5
username: root
password: blah
socket: /var/run/mysqld/mysqld.sock
当我运行这个规范文件时:
require 'spec_helper'
describe Category do
puts "ENV: #{Rails.env}"
it { should validate_presence_of :name }
it { should validate_presence_of :display_name }
it { should validate_presence_of :description }
it { should validate_presence_of :icon }
it { should validate_presence_of :image }
it { should validate_presence_of :parent_category_id }
it { should validate_presence_of :create_time }
end
像这样:
>rspec /path/to/category_spec.rb
我得到:
/home/user/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/abstract/connection_specification.rb:45:in `resolve_hash_connection': database configuration does not specify adapter (ActiveRecord::AdapterNotSpecified)
我也试过像这样设置建立连接:
establish_connection(
:adapter => "mysql2",
:encoding => "utf8",
:reconnect => false,
:database => "main_cat",
:pool => 5,
:username => "root",
:password => "blah",
:socket => "/var/run/mysqld/mysqld.sock")
这导致相同的异常。(适配器未指定)
奇怪的是,如果我完全放弃建立连接并通过 database.yml 文件应用完全相同的连接配置,如下所示:
test:
adapter: mysql2
encoding: utf8
reconnect: false
database: main_cat
pool: 5
username: root
password: blah
socket: /var/run/mysqld/mysqld.sock
有用。
似乎 Rails 完全忽略了建立连接......我是否缺少一些应用程序级配置设置或其他东西?如何让 Rails 识别建立连接,以便我可以将不同的模型放在不同的数据库中?
非常感激!