Last active
August 29, 2015 14:09
-
-
Save mayfer/93c3304faacfd8b7dbda to your computer and use it in GitHub Desktop.
simple ORM example for a Book class
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
# This example demonstrates how to generate SQL statements | |
# to fetch and save objects to a database. | |
# Warning: It does not do the actual database calls. just returns the statements. | |
class Book | |
attr_accessor :id, :title, :author_id, :subject_id | |
def initialize(id, title, author_id, subject_id) | |
@id = id | |
@title = title | |
@author_id = author_id | |
@subject_id = subject_id | |
end | |
def to_s | |
@title | |
end | |
def save | |
if @id | |
update | |
else | |
create | |
end | |
end | |
def update | |
# make sure to use escaped arguments when you implement this yourself. | |
# (with placeholders instead of actual values being passed into the string) | |
sql = "UPDATE books SET title=#{@title} WHERE id=#{id}" | |
end | |
def create | |
sql = "INSERT INTO books (title) VALUES (#{@title})" | |
end | |
def all | |
sql = "SELECT * FROM books" | |
end | |
def self.search(terms) | |
sql = "SELECT * FROM books WHERE title ILIKE '%#{terms}%'" | |
# CONNECTION does not exist, replace it with your own SQL connection object and exec call | |
results = CONNECTION.execute(sql) | |
books = [] | |
results.each do |row| | |
book = Book.new(row["id"], row["title"], row["author_id"], row["subject_id"]) | |
books << book | |
end | |
books | |
end | |
end | |
results = Book.search("space") | |
puts results | |
book = Book.new | |
book.title = "How to confuse students in a lecture" | |
puts book.save | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment