code_aks
code_aks

Reputation: 2074

rake db:create throws “database does not exist” error with postgresql

I'm using rails 5.2.2.1 with postgresql 10.6, and I'm not able to create a database in my development environment. When I run

bin/rake db:create

or

bundle exec rake db:create

I get

rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "mplaces_dev" does not exist
/home/user/.rvm/gems/ruby-2.5.3/gems/activerecord-5.2.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:696:in `rescue in connect'
/home/user/.rvm/gems/ruby-2.5.3/gems/activerecord-5.2.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:691:in `connect'    

I am trying to create the database so, naturally, it does not exist. However rails should create it ... Here's my config/database.yml:

development:
 adapter: postgis
 database: mplaces_dev
 encoding: unicode
 username: postgres
 password: postgres
 host: localhost
 postgis_extension: true
 schema_search_path: "public,postgis"

However I also created all the extensions. I've been at this for more than an hour, and still can't understand why this is happening ...

Thanks!

Upvotes: 5

Views: 1930

Answers (1)

Aymen Bou
Aymen Bou

Reputation: 1109

For me, it was because I had some Model dependant logic in one of my initializers.

This was never a problem before, but since setting up CI, I need to modify my project so that it excludes some logic from the initializers for the Model dependent part.

For initializer_example.rb:

# non model dependent
Aws.config(secret_key: xyz, access_key: zyx)

# model dependent
User.where(admin:true).update(field: value)

To:

# non model dependent
Aws.config(secret_key: xyz, access_key: zyx)

# model dependent
db_loaded = ::ActiveRecord::Base.connection_pool.with_connection(&:active?) rescue false
if db_loaded
    User.where(admin:true).update(field: value)
end

This will run the initializer as usual ONLY if the database has been loaded (i.e in production)

As for my CI/Testing environments, I modify the RSPEC's to load the initializer again (bad practice I know) before testing (of course by this stage the environment should be configured so this time it will run as normal) using the code:

load "#{Rails.root}/config/initializers/initializer_example.rb"

Upvotes: 5

Related Questions