Set up CRUD for Companies

master
Matt Huntington 8 years ago
parent 4c8aecf1fe
commit 7793cb0f4e

@ -0,0 +1,23 @@
class CompaniesController < ApplicationController
skip_before_action :verify_authenticity_token
def index
render json: Company.all
end
def show
render json: Company.find(params["id"])
end
def create
render json: Company.create(params["company"])
end
def delete
render json: Company.delete(params["id"])
end
def update
render json: Company.update(params["id"], params["company"])
end
end

@ -0,0 +1,35 @@
class Company
# connect to postgres
DB = PG.connect(host: "localhost", port: 5432, dbname: 'contacts')
def initialize(opts = {})
@id = opts["id"].to_i
@name = opts["name"]
@age = opts["industry"]
end
def self.all
results = DB.exec("SELECT * FROM companies;")
return results.map { |result| Company.new(result) }
end
def self.find(id)
results = DB.exec("SELECT * FROM companies WHERE id=#{id};")
return Company.new(results.first)
end
def self.create(opts={})
results = DB.exec("INSERT INTO companies (name, industry) VALUES ( '#{opts["name"]}', '#{opts["industry"]}' );")
return { created:true }
end
def self.delete(id)
results = DB.exec("DELETE FROM companies WHERE id=#{id};")
return { deleted: true }
end
def self.update(id, opts={})
results = DB.exec("UPDATE companies SET name='#{opts["name"]}', industry='#{opts["industry"]}' WHERE id=#{id} ;")
return { updated: true }
end
end

@ -12,4 +12,9 @@ Rails.application.routes.draw do
delete '/locations/:id', to: 'locations#delete'
put '/locations/:id', to: 'locations#update'
get '/companies', to: 'companies#index'
get '/companies/:id', to: 'companies#show'
post '/companies', to: 'companies#create'
delete '/companies/:id', to: 'companies#delete'
put '/companies/:id', to: 'companies#update'
end

Loading…
Cancel
Save