DEV Community

Brittany
Brittany

Posted on • Updated on

Day 8: #100DaysofCode - Setting up Sinatra Database - Part 4

Song of the day

Okay, so you have got the basic set up of your application, we need to create a basic database with users and a way for users to add content under posts. In order to do that you will have to create a migration.

First, let's start with running rake -T and see all the options we have available to us.

rake console                # Starts console
rake db:create              # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (...
rake db:create_migration    # Create a migration (parameters: NAME, VERSION)

rake db:drop                # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (us...
rake db:environment:set     # Set the environment value for the database
rake db:fixtures:load       # Loads fixtures into the current environment's database
rake db:migrate             # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status      # Display status of migrations
rake db:prepare             # Runs setup if database does not exist, or runs migrations if it does
rake db:rollback            # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear  # Clears a db/schema_cache.yml file
rake db:schema:cache:dump   # Creates a db/schema_cache.yml file
rake db:schema:dump         # Creates a db/schema.rb file that is portable against any DB supported by Active Record
rake db:schema:load         # Loads a schema.rb file into the database
rake db:seed                # Loads the seed data from db/seeds.rb
rake db:seed:replant        # Truncates tables of each database for current environment and loads the seeds
rake db:setup               # Creates the database, loads the schema, and initializes with the seed data (use db:reset ...
rake db:structure:dump      # Dumps the database structure to db/structure.sql
rake db:structure:load      # Recreates the databases from the structure.sql file
rake db:version             # Retrieves the current schema version number
Enter fullscreen mode Exit fullscreen mode

As you can see if we run rake db:create_migration with the correct parameters it will create a migration

So, lets create a users and posts migration by running the following code.

rake db:create_migration NAME=create_users and rake db:create_migration NAME=create_posts

You will discover that this will create two files in your db/migrate directory. We will need to add the following code into the Users table.

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :username
    end
  end
end

Enter fullscreen mode Exit fullscreen mode

Next, we will need to add the following code into the Posrs table.

class CreatePosts < ActiveRecord::Migration[6.0]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :content
      t.integer :user_id
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

You will also need to create two new files in models, one named user.rb and one named post.rb, which will inherit ActiveRecord::Base.

class Post < ActiveRecord::Base
  belongs_to :user
end
Enter fullscreen mode Exit fullscreen mode
class User < ActiveRecord::Base
  has_many :posts
end
Enter fullscreen mode Exit fullscreen mode

Lastly we will need to migrate these two tables by running, rake db:migrate

If you run into errors while running rake db:migrate please check you ActiveRecord::Migration version

If everything ran correctly, you should now be able to run rake console or type tux you will be able to modify your database including creating users and posts.

u = User.create(username: username= "John")
Enter fullscreen mode Exit fullscreen mode

creates a user

p = Post.create(title: title= "first title", content: content="this is content")
Enter fullscreen mode Exit fullscreen mode

creates a user

p.user = u
Enter fullscreen mode Exit fullscreen mode

sets the user_id in post equal to the 'u' user

p
Enter fullscreen mode Exit fullscreen mode

Should return the following:

=> #<Post:0x00007f8358b5eea0 id: 1, title: "first title", content: "this is content", user_id: 1>

Great! Now your database is all setup :) Play around in the rake console and tux to build up your database.

#100DaysofCode Github Repo

Top comments (0)