Skip to content

Instantly share code, notes, and snippets.

@vanakenm
Created March 4, 2016 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanakenm/1fc1c1313f5662c9b02b to your computer and use it in GitHub Desktop.
Save vanakenm/1fc1c1313f5662c9b02b to your computer and use it in GitHub Desktop.
# Before using, download the database [from the lecture](http://karr.lewagon.org/assets/02_sql_crud_doctors-cf43cfaf07025130e638de583d55e0ec.db)
# and save it as "doctors.db" in the same folder as this file
require 'sqlite3'
DB = SQLite3::Database.new("doctors.db")
class Doctor
attr_reader :id
attr_accessor :name, :age, :specialty
def initialize(attributes)
@id = attributes[:id]
@name = attributes[:name]
@age = attributes[:age]
@speciality = attributes[:specialty]
end
# Get all Doctors (class method as don't need an object to call it)
def self.all
DB.execute("SELECT * FROM doctors;").map do |row|
Doctor.new(id: row[0], name: row[1], age: row[2], specialty: row[3])
end
end
# Get a single Doctor from its id (class method as don't need an object to call it)
def self.find(id)
# Retrieve record from db
row = DB.execute("SELECT * FROM doctors WHERE id = ?;", id).first
# Create a new Doctor object
Doctor.new(id: row[0], name: row[1], age: row[2], specialty: row[3])
end
# Destroy the current doctor (instance method)
def destroy
DB.execute("DELETE FROM doctors WHERE id = ?;", @id)
end
# Save the current doctor (instance method)
def save
if(@id)
DB.execute("UPDATE doctors set name = ?, age = ?, specialty = ? WHERE id = ?;",
@name,
@age,
@specialty,
@id
)
else
DB.execute("INSERT INTO doctors (name, age, specialty) VALUES (?, ?, ?);",
@name,
@age,
@specialty
)
@id = DB.last_insert_row_id
end
end
end
# Create a new Doctor:
# green = Doctor.new(name: "Green", age: 25, specialty: "Oncologist")
# green.save
# Find all doctors:
# doctors = Doctor.all
# Find a single Doctor
# john = Doctor.find(1)
# Destroy a Doctor
# john.destroy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment