【问题标题】:AdapterNotSpecified when using establish_connection on ActiveRecord model在 ActiveRecord 模型上使用建立连接时的 AdapterNotSpecified
【发布时间】:2025-12-31 22:55:01
【问题描述】:

这是一个示例模型。

class MyModel < ApplicationRecord
    establish_connection "other_db_#{Rails.env}"
end

这里是 database.yml 文件。

default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

other_db_development:
  <<: *default
  database: db/my_other_database_development.sqlite

other_db_production:
  <<: *default
  database: db/my_other_database_production.sqlite

当我尝试访问模型时,出现以下错误:

ActiveRecord::AdapterNotSpecified:数据库配置未指定适配器

【问题讨论】:

    标签: ruby-on-rails ruby database activerecord


    【解决方案1】:

    要使其正常工作,您需要进行更改:

    class MyModel < ApplicationRecord
        establish_connection "other_db_#{Rails.env}"
    end
    

    class MyModel < ApplicationRecord
        establish_connection "other_db_#{Rails.env}".to_sym
    end
    

    【讨论】: