Rails 5.x: Specified 'sqlite3' for database adapter, but the gem is not loaded. Add `gem 'sqlite3'` to your Gemfile

エラー内容

Model作成時に、sqlite3がloadされていない旨のメッセージが出力される。

$ rails g scaffold Hoge title:string image:string link:string
/home/hoge/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/activerecord-5.1.6.1/lib/active_record/connection_adapters/connection_specification.rb:188:in `rescue in spec': Specified 'sqlite3' for database adapter, but the gem is not loaded. Add `gem 'sqlite3'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). (Gem::LoadError)

原因

sqlite1.4がreleaseされたが, rails的には1.3.xにしか対応していない。
rails newで作成されるデフォルトのGemfileにはsqliteのバージョン指定がないため、1.4がbundle installされ上記エラーとなる。
Rails6では修正され, 5.2.3にもバックポートされるらしい。

対処

Gemfileを以下の通り1.3をバージョン指定するよう修正

  • before
'sqlite3'
'sqlite3', '~> 1.3', ' < 1.4.0'
  • 以下を実行して指定バージョンをインストール
bundle up sqlite3

Specified 'sqlite3' for database adapter, but the gem is not loaded. : rails