Git Product home page Git Product logo

sinatra-activerecord-setup's Introduction

Sinatra Active Record Setup

Objectives

  • Setup a database in a Sinatra application.
  • Create and use a Rakefile to run ActiveRecord migrations.
  • Use ActiveRecord in a Sinatra application.

Overview

Sinatra doesn't come with database support out of the box, but it's relatively easy to configure. In general, we'll be working from templates that have this pre-built, but it's good to understand what's going on under the hood. We're going to practice adding a database to our Sinatra applications.

Instructions

Fork and clone this repository to get started! We have a basic sinatra application stubbed out with an app.rb file acting as the controller.

Adding Your Gems

Currently, a few gems are already present in our Gemfile:

gem 'sinatra'
gem 'thin'
gem 'require_all'


group :development do
	gem 'shotgun'
	gem 'pry'
end

To get Sinatra working with ActiveRecord, First, we'll add three gems to allow us to use ActiveRecord: activerecord version 5.2, sinatra-activerecord, and rake. The activerecord gem gives us access to the magical database mapping and association powers. The rake gem, short for "ruby make", is a package that lets us quickly create files and folders, and automate tasks such as database creation, and the sinatra-activerecord gem gives us access to some awesome Rake tasks. Make sure those three gems are added in your Gemfile:

  gem 'sinatra'
  gem 'thin'
  gem 'require_all'
  gem 'activerecord', '5.2'
  gem 'sinatra-activerecord'
  gem 'rake'

Into our development group, we'll add two other gems: sqlite3 and tux. sqlite3 is our database adapter gem - it's what allows our Ruby application to communicate with a SQL database. tux will give us an interactive console that pre-loads our database and ActiveRecord relationships for us. Since we won't use either of these in production, we put them in our :development group - this way, they won't get installed on our server when we deploy our application.

  gem 'sinatra'
  gem 'thin'
  gem 'require_all'
  gem 'activerecord', '5.2'
  gem 'sinatra-activerecord'
  gem 'rake'

  group :development do
    gem 'shotgun'
    gem 'pry'
    gem 'tux'
    gem 'sqlite3', '~> 1.3.6'
  end

Our Gemfile is up to date - awesome! Go ahead and run bundle install to get your system up to speed.

Connecting to the Database

We now have access to all of the gems that we need, but we still need to set up a connection to our database. Add the following block of code to your environment.rb file (underneath Bundler.require(:default, ENV['SINATRA_ENV'])).

configure :development do
  set :database, 'sqlite3:db/database.db'
end

This sets up a connection to a sqlite3 database named "database.db", located in a folder called "db." If we wanted our .db file to be called dogs.db, we could simply change the name of this file:

configure :development do
  set :database, 'sqlite3:db/dogs.db'
end

But for now, database.db is a great name. Notice that this didn't actually create those files or folders yet - that's how Rake will help us.

Making a Rakefile

As we mentioned, rake gives us the ability to quickly make files and set up automated tasks. We define these in a file called Rakefile. First, create a Rakefile in the root of our project directory. In the Rakefile, we'll require our config/environment.rb file to load up our environment, as well as "sinatra/activerecord/rake" to get Rake tasks from the sinatra-activerecord gem.

require './config/environment'
require 'sinatra/activerecord/rake'

In the terminal, type rake -T to view all of the available rake tasks. You should see the following output:

rake db:create              # Creates the database from DATABASE_URL or config/database.yml for...
rake db:create_migration    # Create a migration (parameters: NAME, VERSION)
rake db:drop                # Drops the database from DATABASE_URL or config/database.yml for t...
rake db:fixtures:load       # Load 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:rollback            # Rolls the schema back to the previous version (specify steps w/ S...
rake db:schema:cache:clear  # Clear a db/schema_cache.dump file
rake db:schema:cache:dump   # Create a db/schema_cache.dump file
rake db:schema:dump         # Create a db/schema.rb file that is portable against any DB suppor...
rake db:schema:load         # Load a schema.rb file into the database
rake db:seed                # Load the seed data from db/seeds.rb
rake db:setup               # Create the database, load the schema, and initialize with the see...
rake db:structure:dump      # Dump the database structure to db/structure.sql
rake db:structure:load      # Recreate the databases from the structure.sql file
rake db:version             # Retrieves the current schema version number

Testing it Out

Let's test out our handiwork by creating a dogs table with two columns: name and breed. First, let's create our migration:

rake db:create_migration NAME=create_dogs

You should see the following output:

=># db/migrate/20150914201353_create_dogs.rb

The beginning of the file is a timestamp - yours should reflect the time that your create_dogs file was created! You've now created your first database migration inside of the db folder.

Inside of the migration file, remove the default change method (we'll come back to this), and add methods for up and down.

class CreateDogs < ActiveRecord::Migration[5.2]
  def up
  end

  def down
  end
end

Important: When we create migrations with ActiveRecord, we must specify the version we're using just after ActiveRecord::Migration. In this case, we're using 5.2, so all the examples here will show ActiveRecord::Migration[5.2]. This version may differ depending on the lab. If this number does not match the version in your Gemfile.lock, your migration will cause an error.

Our up method should create our table with name and breed columns. Our down method should drop the table.

class CreateDogs < ActiveRecord::Migration[5.2]
  def up
    create_table :dogs do |t|
      t.string :name
      t.string :breed
    end
  end

  def down
    drop_table :dogs
  end
end

Now, run the migration from the terminal with rake db:migrate.

rake db:migrate SINATRA_ENV=development

Why add SINATRA_ENV=development, you might ask? Well, remember the top line of config/environment.rb? It's telling Sinatra that it should use the "development" environment for both shotgun and the testing suite. Therefore, we want to make sure our migrations run on the same environment as well, and specifying SINATRA_ENV=development allows us to do that.

You should see the following output:

== 20150914201353 CreateDogs: migrating =======================================
-- create_table(:dogs)
   -> 0.0019s
== 20150914201353 CreateDogs: migrated (0.0020s) ==============================

The change Method

The change method is actually a shorter way of writing up and down methods. We can refactor our migration to look like this:

class CreateDogs < ActiveRecord::Migration[5.2]
  def change
    create_table :dogs do |t|
      t.string :name
      t.string :breed
    end
  end

end

While the rollback (down) method is not included, it's implicit in the change method. Rolling back the database would work in exactly the same way as using the down method.

sinatra-activerecord-setup's People

Contributors

annjohn avatar danielseehausen avatar deniznida avatar dfenjves avatar dstoll243 avatar franknowinski avatar ihollander avatar ipc103 avatar jakebrady5 avatar jmburges avatar jonbf avatar maxwellbenton avatar pletcher avatar rishter avatar victhevenot avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sinatra-activerecord-setup's Issues

rake -T throws error

LAB:
https://learn.co/tracks/online-software-engineering-structured/sinatra/activerecord/activerecord-setup-in-sinatra?batch_id=1642&track_id=54342

ISSUE:
The user followed along with README but unable to run rake commands. Tried bundle update and uninstalling and reinstalling rake gem.

ERROR:

rake aborted!
NoMethodError: undefined method `configure' for main:Object
/Users/timflood/Workspace/flatiron/code/sinatra-activerecord-setup-onl01-seng-pt-081720/config/environment.rb:3:in `<top (required)>'
/Users/timflood/Workspace/flatiron/code/sinatra-activerecord-setup-onl01-seng-pt-081720/Rakefile:1:in `<top (required)>'
(See full trace by running task with --trace)

This directory doesn't have any specs in it

Can you please put the specs file into the lab directory so that I can mark this lab as completed? See the below. thanks!

[17:43:10] (master) sinatra-activerecord-setup-v-000
// โ™ฅ learn
This directory doesn't appear to have any specs in it.
[17:44

rake does not work

despite adding the necessary gems in the Gemfile and setting the database in environment.rb, rake does not install. I get teh following error:

/usr/local/rvm/gems/ruby-2.6.1/gems/activesupport-4.2.5/lib/active_support/core_ext/object/dupli cable.rb:85: warning: BigDecimal.new is deprecated; use BigDecimal() method instead. rake aborted! Gem::LoadError: Specified 'sqlite3' for database adapter, but the gem is not loaded. Add gem 's
qlite3' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).

Caused by: Gem::LoadError: can't activate sqlite3 (~> 1.3.6), already activated sqlite3-1.4.1. Make sure al l dependencies are added to Gemfile.

bundle install not working

I am not the only person who has a problem with this lab. Bundle Install in not working, so I guess there is a problem with a gemfile in this lab. One of the TCs tried to help me, but we couldn't find the issue. We tried forcing the HTTP instead of HTTPS and it's not working. Any suggestions?

Solution does not match provided code

Hey there, I'm following along with the directions from this lab, and unfortunately when I enter the provided code into the rakefile, it gives me this error:

No Rakefile found (looking for: rakefile, Rakefile, rakefile.rb, Rakefile.rb)
/Users/helloamandamurphy/.rvm/gems/ruby-2.5.3/gems/rake-12.3.2/exe/rake:27:in `<top (required)>'
/Users/helloamandamurphy/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:24:in `eval'
/Users/helloamandamurphy/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:24:in `<main>'
(See full trace by running task with --trace)

That's fine and dandy, but when I went to look at the solution to see if I had added it in the wrong place, I noticed the solution code provided on the repo is not the solution for the lab and is missing the code provided in the walkthrough. There is no rakefile in the solution and the gems have not been updated. I know there is no spec for the lab, but I still want to be able to double check that I'm following the lab properly.

IDE is not responding to control+C when server is on.

Hello,
I can't log off the server using control + C. It is like the IDE is dead, no response. Only way is close the IDE and start again.
Shotgun/WEBrick on http://0.0.0.0:9393/
[2019-04-10 19:16:28] INFO WEBrick 1.4.2
[2019-04-10 19:16:28] INFO ruby 2.6.1 (2019-01-30) [x86_64-linux]
[2019-04-10 19:16:28] INFO WEBrick::HTTPServer#start: pid=16501 port=42882
D, [2019-04-10T19:16:38.262414 #17179] DEBUG -- : (0.2ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
D, [2019-04-10T19:16:38.272245 #17179] DEBUG -- : Article Load (0.2ms) SELECT "articles".* FROM "articles"
71.190.142.19 - - [10/Apr/2019:19:16:38 +0000] "GET / HTTP/1.1" 200 155 0.0077
D, [2019-04-10T19:16:42.922256 #17511] DEBUG -- : (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
71.190.142.19 - - [10/Apr/2019:19:16:42 +0000] "GET /new HTTP/1.1" 404 536 0.0039
D, [2019-04-10T19:16:43.855807 #17565] DEBUG -- : (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
71.190.142.19 - - [10/Apr/2019:19:16:43 +0000] "GET /sinatra/404.png HTTP/1.1" 200 18893 0.0061
D, [2019-04-10T19:16:59.862456 #17982] DEBUG -- : (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
71.190.142.19 - - [10/Apr/2019:19:16:59 +0000] "GET /articles/new HTTP/1.1" 200 274 0.0060
D, [2019-04-10T19:17:28.961154 #18057] DEBUG -- : (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
71.190.142.19 - - [10/Apr/2019:19:17:28 +0000] "GET /articles/new HTTP/1.1" 200 276 0.0061
D, [2019-04-10T19:18:26.881367 #18134] DEBUG -- : (0.2ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
71.190.142.19 - - [10/Apr/2019:19:18:26 +0000] "GET /articles/new HTTP/1.1" 200 302 0.0062
D, [2019-04-10T19:18:36.004944 #18168] DEBUG -- : (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
71.190.142.19 - - [10/Apr/2019:19:18:36 +0000] "GET /articles?title=zaza&content=dkjlfsajflkd&submit=Submit HTTP/1.1" 404 541 0.0039
D, [2019-04-10T19:20:45.146605 #18245] DEBUG -- : (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
71.190.142.19 - - [10/Apr/2019:19:20:45 +0000] "GET /articles?title=zaza&content=dkjlfsajflkd&submit=Submit HTTP/1.1" 404 541 0.0041
D, [2019-04-10T19:20:46.107568 #18278] DEBUG -- : (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
71.190.142.19 - - [10/Apr/2019:19:20:46 +0000] "GET /sinatra/404.png HTTP/1.1" 304 - 0.0047
c^C
^Cccquit
^C^C^C^C^C
^Y
^C^C^C
quit
^C

Code in config.ru throws errors

config.ru
This starter code throws errors in server:

require './config/environment'
if ActiveRecord::Base.connection.migration_context.needs_migration?
raise 'Migrations are pending. Run rake db:migrate to resolve the issue.'
end
run ApplicationController

NoMethodError: undefined method `migration_context' for #ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x007ff66dd3be48 Did you mean? migration_keys

**Change to:
require './config/environment'

if ActiveRecord::Migrator.needs_migration?
raise 'Migrations are pending. Run rake db:migrate SINATRA_ENV=test to resolve the issue.'
end

run ApplicationController**

rake would not work until I changed sqlite version to 1.3.6

Readme says to require sqlite3 gem like so:
group :development do gem 'shotgun' gem 'pry' gem 'tux' gem 'sqlite3' end

Doing so resulted in this error when trying to run rake -T
rake aborted! Gem::LoadError: 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).

Googled and found this solution on StackOverflow:
https://stackoverflow.com/questions/54527277/cant-activate-sqlite3-1-3-6-already-activated-sqlite3-1-4-0

To quote:

...I removed the gem that I thought was giving me an error, by
gem uninstall sqlite3 -v 1.4.0
and instead, used in my gem file. gem 'sqlite3', '~> 1.3.6'
Ran the bundle update and it worked like a charm for me.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.