Julian Veling
Julian Veling

Reputation: 357

ActiveRecord, Sinatra and Postgres - cant link to my db

I cant seem to get my Postgres db to link to my Sinatra app using Active record. I'm getting the following error when I run db:migrate

ActiveRecord::NoDatabaseError: FATAL:  database "localhost/till" does not exist

I ran dbcreate mydb and that went through without problem, and it definitely exists.

I have a config folder and an environment.rb file with

db = URI.parse(ENV['DATABASE_URL'] || 'postgres:///localhost/mydb')

ActiveRecord::Base.establish_connection(
  adapter: db.scheme == 'postgres' ? 'postgresql' : db.scheme,
  host: db.host,
  username: db.user,
  password: db.password,
  database: db.path[1..-1],
  encoding: 'utf8'
)

Im referencing the file in my app.rb so thats not the problem. Any help gratefully appreciated.

Upvotes: 1

Views: 801

Answers (1)

thesecretmaster
thesecretmaster

Reputation: 1984

Do you have a migration file that you are using to create the tables in the database? When you migrate that should generate the schema file. To create a migration file, cd to your app folder and enter the terminal command bundle exec rake db:create_migration NAME=my_migration_name. That will create a db folder in your app folder which will contain a migrate folder. In the migrate folder there will be a file. That will will look like this:

class Migration < ActiveRecord::Migration
  def change
  end
end

In the change function is where you can create tables. To create a table add into the change function a create_table function, as shown below.

class MyMigrationFile < ActiveRecord::Migration
  def change
    create_table :my_table_name do |i|
      i.string :my_column_name
      # string is the type of variable this column will store, you can change that if you want
    end
  end
end

Then to actually create the tables you need to migrate. To migrate, or actually create the tables enter the terminal command bundle exec rake db:migrate. That will generate your schema file.

Upvotes: 1

Related Questions