From ca48eaa12133920e84298016f41f6a5f186a5f5b Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Sun, 25 Mar 2018 18:28:54 -0400 Subject: [PATCH] person.all for many to many --- app/models/location.rb | 6 ++--- app/models/person.rb | 59 +++++++++++++++++++++++++++++------------- 2 files changed, 44 insertions(+), 21 deletions(-) diff --git a/app/models/location.rb b/app/models/location.rb index f4d18a2..433985d 100644 --- a/app/models/location.rb +++ b/app/models/location.rb @@ -27,10 +27,9 @@ class Location SQL ) locations = [] - current_location_id = nil + last_location_id = nil results.each do |result| - if result["id"] != current_location_id - current_location_id = result["id"] + if result["id"] != last_location_id locations.push( Location.new({ "id" => result["id"], @@ -40,6 +39,7 @@ class Location "inhabitants" => [] }) ) + last_location_id = result["id"] end if result["person_id"] new_person = Person.new({ diff --git a/app/models/person.rb b/app/models/person.rb index ef289e9..bf085d4 100644 --- a/app/models/person.rb +++ b/app/models/person.rb @@ -22,34 +22,57 @@ class Person people.*, locations.street, locations.city, - locations.state + locations.state, + companies.id AS company_id, + companies.name AS company, + companies.industry FROM people LEFT JOIN locations ON people.home_id = locations.id + LEFT JOIN jobs + ON people.id = jobs.person_id + LEFT JOIN companies + ON jobs.company_id = companies.id SQL ) - return results.map do |result| - if result["home_id"] - home = Location.new( + people = [] + last_person_id = nil + results.each do |result| + if result["id"] != last_person_id + last_person_id = result["id"] + if result["home_id"] + home = Location.new( + { + "id" => result["home_id"], + "street" => result["street"], + "city" => result["city"], + "state" => result["state"], + } + ) + else + home = nil + end + new_person = Person.new( { - "id" => result["home_id"], - "street" => result["street"], - "city" => result["city"], - "state" => result["state"], + "id" => result["id"], + "name" => result["name"], + "age" => result["age"], + "home" => home, + "employers" => [] } ) - else - home = nil + people.push(new_person) + end + if result["company_id"] + employer = Company.new({ + "id" => result["company_id"], + "name" => result["company"], + "industry" => result["industry"] + }) + people.last.employers.push(employer) end - Person.new( - { - "id" => result["id"], - "name" => result["name"], - "age" => result["age"], - "home" => home, - } - ) end + return people end def self.find(id)