Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Intro to Databases (Rails Girls PHL)

Intro to Databases (Rails Girls PHL)

A quick intro to databases for Rails Girls PHL.

Ernesto Tagwerker

December 03, 2016
Tweet

More Decks by Ernesto Tagwerker

Other Decks in Programming

Transcript

  1. $ rails new --help # database # (options: mysql/oracle/postgresql/sqlite3/ frontbase/ibm_db/sqlserver/jdbcmysql/

    jdbcsqlite3/jdbcpostgresql/jdbc) $ rails new polls —database=postgresql $ rails new polls # defaults to sqlite3
  2. Rails Migrations # db/migrate/20161124163416_create_topics.rb class CreateTopics < ActiveRecord::Migration def change

    create_table :topics do |t| t.string :title t.text :description t.timestamps null: false end end end
  3. Rails Migrations $ rake db:migrate == 20161124163416 CreateTopics: migrating =====================================

    -- create_table(:topics) -> 0.0496s == 20161124163416 CreateTopics: migrated (0.0497s) ============================
  4. Rails Migrations CREATE TABLE `topics` ( `id` int(11) NOT NULL

    AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `description` text, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`) )
  5. Models # app/models/vote.rb class Vote < ActiveRecord::Base belongs_to :user belongs_to

    :topic end # app/models/topic.rb class Topic < ActiveRecord::Base has_many :votes end # app/models/user.rb class User < ActiveRecord::Base has_many :votes end
  6. Models (create) $ rails console > Topic.create(title: 'Intro to Database',

    description: 'This is awesome!') SQL (1.4ms) INSERT INTO `topics` (`title`, `description`, `created_at`, `updated_at`) VALUES ('Intro to Database', 'This is awesome!', '2016-11-24 16:57:13', '2016-11-24 16:57:13') => #<Topic id: 1, title: "Intro to Database", description: "This is awesome!", created_at: "2016-11-24 16:57:13", updated_at: "2016-11-24 16:57:13">
  7. Models (retrieve) > topic = Topic.find 1 Topic Load (1.6ms)

    SELECT `topics`.* FROM `topics` WHERE `topics`.`id` = 1 LIMIT 1 => #<Topic id: 1, title: "Intro to Database", description: "This is awesome!", created_at: "2016-11-24 16:57:13", updated_at: "2016-11-24 16:57:13">
  8. Models (update) > topic.title = "Intro to Databases" => "Intro

    to Databases" > topic.save SQL (2.3ms) UPDATE `topics` SET `title` = 'Intro to Databases', `updated_at` = '2016-11-24 17:00:47' WHERE `topics`.`id` = 1 => true
  9. Models (destroy) > topic.delete SQL (10.0ms) DELETE FROM `topics` WHERE

    `topics`.`id` = 1 => #<Topic id: 1, title: "Intro to Databases", description: "This is awesome!", created_at: "2016-11-24 16:57:13", updated_at: "2016-11-24 17:00:47">