From 065cfa065e82611cc245132b37857ac4ed69ebb4 Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Fri, 23 Mar 2018 01:04:51 -0400 Subject: [PATCH] inhabitants array --- app/models/location.rb | 78 ++++++++++++++++++++++++++++++++++++++---- app/models/person.rb | 5 --- 2 files changed, 72 insertions(+), 11 deletions(-) diff --git a/app/models/location.rb b/app/models/location.rb index 92c39aa..f4d18a2 100644 --- a/app/models/location.rb +++ b/app/models/location.rb @@ -1,6 +1,6 @@ class Location attr_reader :id, :street, :city, :state, :inhabitants - # connect to postgres + DB = PG.connect(host: "localhost", port: 5432, dbname: 'contacts') def initialize(opts = {}) @@ -8,17 +8,83 @@ class Location @street = opts["street"] @city = opts["city"] @state = opts["state"] - @inhabitants = Person.findByHomeId(@id) + if opts["inhabitants"] + @inhabitants = opts["inhabitants"] + end end def self.all - results = DB.exec("SELECT * FROM locations;") - return results.map { |result| Location.new(result) } + results = DB.exec( + <<-SQL + SELECT + locations.*, + people.id AS person_id, + people.name, + people.age + FROM locations + LEFT JOIN people + ON locations.id = people.home_id + SQL + ) + locations = [] + current_location_id = nil + results.each do |result| + if result["id"] != current_location_id + current_location_id = result["id"] + locations.push( + Location.new({ + "id" => result["id"], + "street" => result["street"], + "city" => result["city"], + "state" => result["state"], + "inhabitants" => [] + }) + ) + end + if result["person_id"] + new_person = Person.new({ + "id" => result["person_id"], + "name" => result["name"], + "age" => result["age"], + }) + locations.last.inhabitants.push(new_person) + end + end + return locations end def self.find(id) - results = DB.exec("SELECT * FROM locations WHERE id=#{id};") - return Location.new(results.first) + results = DB.exec( + <<-SQL + SELECT + locations.*, + people.id AS person_id, + people.name, + people.age + FROM locations + LEFT JOIN people + ON locations.id = people.home_id + WHERE locations.id=#{id}; + SQL + ) + inhabitants = [] + results.each do |result| + if result["person_id"] + inhabitants.push Person.new({ + "id" => result["person_id"], + "name" => result["name"], + "age" => result["age"] + }) + end + end + + return Location.new({ + "id" => results.first["id"], + "street" => results.first["street"], + "city" => results.first["city"], + "state" => results.first["state"], + "inhabitants" => inhabitants + }) end def self.create(opts={}) diff --git a/app/models/person.rb b/app/models/person.rb index fbf6808..ddb83d1 100644 --- a/app/models/person.rb +++ b/app/models/person.rb @@ -126,9 +126,4 @@ class Person ) return Person.new(results.first) end - - def self.findByHomeId(home_id) - results = DB.exec("SELECT id, name, age FROM people WHERE home_id = #{home_id}") - return results.map { |result| Person.new(result) } - end end