AR命令行应用中sqlite3 gem加载失败问题排查
我正在开发一个基于Active Record做数据库交互的命令行应用,目前仅支持Postgres,希望新增SQLite3支持。我在gemspec文件中添加了sqlite3作为运行时依赖并执行bundle install,但通过rspec运行应用时出现如下错误:
LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? can't activate sqlite3 (~> 1.4), already activated sqlite3-2.0.2-x86_64-linux-gnu. Make sure all dependencies are added to Gemfile. # ./vendor/bundle/ruby/3.2.0/gems/activerecord-7.1.3.3/lib/active_record/connection_adapters/sqlite3_adapter.rb:14:in `<top (required)>' # ./vendor/bundle/ruby/3.2.0/gems/activerecord-7.1.3.3/lib/active_record/connection_adapters/abstract/connection_handler.rb:333:in `resolve_pool_config' # ./vendor/bundle/ruby/3.2.0/gems/activerecord-7.1.3.3/lib/active_record/connection_adapters/abstract/connection_handler.rb:134:in `establish_connection' # ./vendor/bundle/ruby/3.2.0/gems/activerecord-7.1.3.3/lib/active_record/connection_handling.rb:53:in `establish_connection' # ./vendor/bundle/ruby/3.2.0/gems/activerecord-import-1.7.0/lib/activerecord-import/import.rb:256:in `establish_connection'
我也曾尝试在gemspec中添加sqlite3-ruby gem,但遇到相同错误。我了解AR 7.1内置了SQLite3适配器,但这是否意味着无需在gemspec中添加该gem?我尝试移除它,却出现类似错误:
LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile. # ./vendor/bundle/ruby/3.2.0/gems/activerecord-7.1.3.3/lib/active_record/connection_adapters/sqlite3_adapter.rb:14:in `<top (required)>' # ./vendor/bundle/ruby/3.2.0/gems/activerecord-7.1.3.3/lib/active_record/connection_adapters/abstract/connection_handler.rb:333:in `resolve_pool_config' # ./vendor/bundle/ruby/3.2.0/gems/activerecord-7.1.3.3/lib/active_record/connection_adapters/abstract/connection_handler.rb:134:in `establish_connection' # ./vendor/bundle/ruby/3.2.0/gems/activerecord-7.1.3.3/lib/active_record/connection_handling.rb:53:in `establish_connection' # ./vendor/bundle/ruby/3.2.0/gems/activerecord-import-1.7.0/lib/activerecord-import/import.rb:256:in `establish_connection'
看来确实需要该gem,请问我哪里操作错误了?
解决方案
匹配Active Record的版本约束:Active Record 7.1.3.3对sqlite3 gem的依赖版本是
~> 1.4,但你当前激活的是2.0.2版本,版本不兼容导致激活失败。需要在gemspec中明确指定符合要求的版本:# 在gemspec文件中 spec.add_runtime_dependency "sqlite3", "~> 1.4"若项目同时使用Gemfile,需确保Gemfile中的约束与gemspec一致,避免bundle安装超出范围的版本。
明确适配器与驱动的区别:AR 7.1内置的是SQLite3的适配器代码(负责AR与数据库的交互逻辑),但底层的数据库驱动(sqlite3 gem)并非AR的一部分,必须手动添加依赖才能正常连接SQLite3数据库。
清理并重新安装依赖:执行以下命令清理旧的冲突版本,重新安装符合约束的sqlite3:
bundle clean --force bundle install使用正确的gem名称:
sqlite3-ruby是sqlite3 gem的旧名称,现在已统一为sqlite3,无需添加sqlite3-ruby,直接使用sqlite3即可。
内容的提问来源于stack exchange,提问作者Daniel Doherty

