Skip to content

Instantly share code, notes, and snippets.

@ericodes
Forked from anonymous/03_objects.rb
Created June 3, 2014 16:53
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 ericodes/e861de5bd001c7f90147 to your computer and use it in GitHub Desktop.
Save ericodes/e861de5bd001c7f90147 to your computer and use it in GitHub Desktop.
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