Created
June 3, 2014 15:11
-
-
Save anonymous/45419cf89d34e54e9ec9 to your computer and use it in GitHub Desktop.
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 'pg' | |
require 'pry' | |
class Artist | |
CONN = PG.connect(dbname: 'chinook') | |
attr_accessor :id, :name | |
def self.new_from_row(row) | |
id = row["id"] | |
name = row["name"] | |
new(id, name) | |
end | |
def self.find_by_name(name) | |
sql = <<-SQL | |
SELECT * | |
FROM artists | |
WHERE name=$1 | |
SQL | |
CONN.exec_params(sql, [name]) do |result| | |
result.map do |row| | |
self.new_from_row(row) | |
end | |
end | |
end | |
def self.find(id) | |
sql = <<-SQL | |
SELECT * | |
FROM artists | |
WHERE id=$1 | |
LIMIT 1 | |
SQL | |
CONN.exec_params(sql, [id]) do |result| | |
row = result.first | |
self.new_from_row(row) | |
end | |
end | |
def initialize(id, name) | |
@id = id | |
@name = name | |
end | |
def insert | |
sql = <<-SQL | |
INSERT INTO artists (name) | |
VALUES ($1) | |
RETURNING id | |
SQL | |
@id = CONN.exec_params(sql, [self.name]).first["id"] | |
end | |
def update | |
sql = <<-SQL | |
UPDATE artists | |
SET name=$1 | |
WHERE id=$2 | |
SQL | |
CONN.exec_params(sql, [self.name, self.id]) | |
end | |
def save | |
if self.id | |
update | |
else | |
insert | |
end | |
end | |
def destroy | |
sql = <<-SQL | |
DELETE FROM artists | |
WHERE id=$1 | |
SQL | |
CONN.exec_params(sql, [self.id]) | |
end | |
def albums | |
sql = <<-SQL | |
SELECT * | |
FROM albums | |
WHERE artist_id=$1; | |
SQL | |
CONN.exec_params(sql, [self.id]).to_a | |
end | |
binding.pry | |
end | |
# flim = Artist.new(nil, "Steven and the Flimflams") | |
# flim.save | |
# | |
# flim.name = "Steven and rockets" | |
# flim.save | |
# result = Artist.find_by_name("Steven and rockets") | |
# reunion = Artist.find(281) | |
binding.pry |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment