Created
January 31, 2020 18:17
-
-
Save jonny-gates/35596e9c299e9ea6c45a29820e556f2f to your computer and use it in GitHub Desktop.
SQL-CRUD Livecode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pry-byebug' | |
class Task | |
attr_reader :id | |
attr_accessor :title, :description, :done | |
def initialize(attributes = {}) | |
@id = attributes[:id] | |
@title = attributes[:title] | |
@description = attributes[:description] | |
@done = attributes[:done] || 0 | |
end | |
def self.find(id) | |
# Query the database for a record with id = id | |
result = DB.execute("SELECT * FROM tasks WHERE id = ?", id) | |
# If not found we return nil | |
if result.empty? | |
return nil | |
else | |
# binding.pry | |
hash = result[0] | |
# binding.pry | |
# Create a new task with the result from out DB | |
Task.new(id: hash["id"], title: hash["title"], description: hash["description"], done: hash["done"]) | |
end | |
end | |
def save | |
# If the task exists in the DB, it will have an ID, otherwise ID will be nil | |
if @id # nil = false any integer=true | |
DB.execute("UPDATE tasks SET title = ?, description = ?, done = ? WHERE id = ?", @title, @description, @done, @id) | |
else | |
DB.execute("INSERT INTO tasks (title, description, done) VALUES (?, ?, ?)", @title, @description, @done) | |
@id = DB.last_insert_row_id | |
end | |
end | |
def destroy | |
DB.execute("DELETE FROM tasks WHERE id = #{@id}") | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "sqlite3" | |
DB = SQLite3::Database.new("tasks.db") | |
DB.results_as_hash = true | |
require_relative "task" | |
# TODO: CRUD some tasks | |
# TODO: Implement a find(id) method | |
# Returns an instance of task | |
task1 = Task.find(1) | |
puts "#{task1.title} - #{task1.description}" | |
# Returns nil if not found | |
p Task.find(1000) | |
# TODO: Implement a method which saves an instance | |
task = Task.new(title: "Second task", description: "More to do") | |
task.save | |
p task.id | |
# TODO: Implement a method which updates an instance | |
task.title = "Updated title" | |
task.save | |
p Task.find(task.id) | |
# TODO: Implement a method which deletes an instance | |
find_id = task.id | |
task.destroy | |
p Task.find(find_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment