Search code examples
rubyactiverecordsinatrapsqlsinatra-activerecord

Sinatra db table not created after migration


I am trying to create active record using Sinatra and Sinatra/active record, my migrations are getting migrated to the Postgres database but tables are not getting created in the database, I went through all the possible solutions on stack overflow but its of no use. I tried even deleting my migration files from db/migrate folder but still the same output. What must be the error

Gemfile

source 'https://rubygems.org'

gem "sinatra"
gem "pg"    #for postgres
gem "activerecord" 
gem "sinatra-activerecord"

config.ru

require "./app"
run Sinatra::Application

rakefile.rb

require "./app"
require "sinatra/activerecord/rake"

app.rb

require 'sinatra'
require 'sinatra/activerecord' 
db = URI.parse('postgres://project1:project1@localhost/*****')
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'
 )


class Note < ActiveRecord::Base
end

class CreateNotes < ActiveRecord::Migration
  def up
    create_table :notes do |t|
        t.string    :title
        t.text  :body
        t.timestamps
    end 
  end
  def down
    drop_table  :notes
  end
end

output of migration

user@user-Inspiron-5520:~/rails-apps/project1$ rake db:migrate
== 20150704053019 CreateNotes: migrating      ======================================
== 20150704053019 CreateNotes: migrated (0.0000s)   =============================

db output (psql)

\dt

           List of relations
 Schema |       Name        | Type  |   Owner   
--------+-------------------+-------+-----------
 public | schema_migrations | table | project1
(1 row)

project1=# select * from schema_migrations;
   version     
----------------
20150704053019

(1 row)

note: Project1 user is a super user with all privileges

EDIT

Migrations file 20150704053019_create_notes.rb

class CreateNotes < ActiveRecord::Migration
  def change
  end
end

Solution

  • I would first like to note that @limekin was the first to get the answer, commenting:

    The migration you are using to create notes table is actually kept in app.rb. But the migrate task looks for migrations inside db/migrate. If the migration file you gave at the bottom is inside the right directory, then move the migration definition from app.rb to there.

    I will just go into a bit more detail. The function that you are using to create the table belongs in the migration file, because a migration is what creates, changes and deletes tables, columns, and records.

    So to solve your issue just move the function up in your app file into the change function in your migration file.