From 4c8aecf1fec1bd12b9541b04ca69fae3f2cd5644 Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Wed, 21 Mar 2018 09:13:05 -0400 Subject: [PATCH] Set up CRUD for Locations --- app/controllers/locations_controller.rb | 23 ++++++++++++++++ app/models/location.rb | 36 +++++++++++++++++++++++++ config/routes.rb | 7 +++++ 3 files changed, 66 insertions(+) create mode 100644 app/controllers/locations_controller.rb create mode 100644 app/models/location.rb diff --git a/app/controllers/locations_controller.rb b/app/controllers/locations_controller.rb new file mode 100644 index 0000000..15146d7 --- /dev/null +++ b/app/controllers/locations_controller.rb @@ -0,0 +1,23 @@ +class LocationsController < ApplicationController + skip_before_action :verify_authenticity_token + + def index + render json: Location.all + end + + def show + render json: Location.find(params["id"]) + end + + def create + render json: Location.create(params["location"]) + end + + def delete + render json: Location.delete(params["id"]) + end + + def update + render json: Location.update(params["id"], params["location"]) + end +end diff --git a/app/models/location.rb b/app/models/location.rb new file mode 100644 index 0000000..e962029 --- /dev/null +++ b/app/models/location.rb @@ -0,0 +1,36 @@ +class Location + # connect to postgres + DB = PG.connect(host: "localhost", port: 5432, dbname: 'contacts') + + def initialize(opts = {}) + @id = opts["id"].to_i + @street = opts["street"] + @city = opts["city"] + @state = opts["state"] + end + + def self.all + results = DB.exec("SELECT * FROM locations;") + return results.map { |result| Location.new(result) } + end + + def self.find(id) + results = DB.exec("SELECT * FROM locations WHERE id=#{id};") + return Location.new(results.first) + end + + def self.create(opts={}) + results = DB.exec("INSERT INTO locations (street, city, state) VALUES ( '#{opts["street"]}', '#{opts["city"]}', '#{opts["state"]}' );") + return { created:true } + end + + def self.delete(id) + results = DB.exec("DELETE FROM locations WHERE id=#{id};") + return { deleted: true } + end + + def self.update(id, opts={}) + results = DB.exec("UPDATE locations SET street='#{opts["street"]}', city='#{opts["city"]}', state='#{opts["state"]}' WHERE id=#{id} ;") + return { updated: true } + end +end diff --git a/config/routes.rb b/config/routes.rb index 52b3d71..86d1dec 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -5,4 +5,11 @@ Rails.application.routes.draw do post '/people', to: 'people#create' delete '/people/:id', to: 'people#delete' put '/people/:id', to: 'people#update' + + get '/locations', to: 'locations#index' + get '/locations/:id', to: 'locations#show' + post '/locations', to: 'locations#create' + delete '/locations/:id', to: 'locations#delete' + put '/locations/:id', to: 'locations#update' + end