From d9c43392d6ca8350ae625b9e4a4107ed4ca5edb3 Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Thu, 22 Mar 2018 13:19:32 -0400 Subject: [PATCH] Expand a foreign key to an object --- app/models/location.rb | 3 ++- app/models/person.rb | 9 +++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/app/models/location.rb b/app/models/location.rb index f123bc1..92c39aa 100644 --- a/app/models/location.rb +++ b/app/models/location.rb @@ -1,5 +1,5 @@ class Location - attr_reader :id, :street, :city, :state + attr_reader :id, :street, :city, :state, :inhabitants # connect to postgres DB = PG.connect(host: "localhost", port: 5432, dbname: 'contacts') @@ -8,6 +8,7 @@ class Location @street = opts["street"] @city = opts["city"] @state = opts["state"] + @inhabitants = Person.findByHomeId(@id) end def self.all diff --git a/app/models/person.rb b/app/models/person.rb index b042307..5d9b320 100644 --- a/app/models/person.rb +++ b/app/models/person.rb @@ -1,5 +1,5 @@ class Person - attr_reader :id, :name, :age, :home_id + attr_reader :id, :name, :age, :home # connect to postgres DB = PG.connect(host: "localhost", port: 5432, dbname: 'contacts') @@ -8,7 +8,7 @@ class Person @name = opts["name"] @age = opts["age"].to_i if opts["home_id"] - @home_id = opts["home_id"].to_i + @home = Location.find(opts["home_id"].to_i) end end @@ -61,4 +61,9 @@ 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