Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created May 21, 2014 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mayfer/cf8b7de85d538b3cf4a0 to your computer and use it in GitHub Desktop.
Save mayfer/cf8b7de85d538b3cf4a0 to your computer and use it in GitHub Desktop.
Author ORM example
require 'pg'
class Author
@@conn = PG.connect(
dbname: 'dfq35t7uirbums',
port: 5432,
user: 'bmdjwluxchptuq',
host: 'ec2-54-204-41-178.compute-1.amazonaws.com',
password: 'aEH-cKdr2zoXYUAjI8Xjma5eXK'
)
def initialize(first, last, id=nil)
@first_name = first
@last_name = last
@id = id
end
def to_s
"#{@first_name} #{@last_name}"
end
def to_json
end
def save
result = @conn.exec("INSERT INTO authors (id, first_name, last_name) VALUES (101, '#{@first_name}', '#{@last_name}')")
end
def destroy
@@conn.exec("DELETE FROM authors WHERE id=#{@id}")
end
def self.search(query)
authors = []
@@conn.exec("SELECT * FROM authors WHERE first_name ILIKE '%#{query}%' OR last_name ILIKE '%#{query}%'").each do |row|
author = Author.new(row["first_name"], row["last_name"], row["id"])
authors << author
end
authors
end
def self.all
authors = []
@@conn.exec("SELECT * FROM authors").each do |row|
author = Author.new(row["first_name"], row["last_name"], row["id"])
authors << author
end
authors
end
end
authors = Author.search('Poppy')
puts authors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment