Create a join table

master
Matt Huntington 8 years ago
parent 065cfa065e
commit 8d410f6d37

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

@ -0,0 +1,49 @@
class Job
attr_reader :id, :job_id, :company_id
# connect to postgres
DB = PG.connect(host: "localhost", port: 5432, dbname: 'contacts')
def initialize(opts = {})
@id = opts["id"].to_i
@person_id = opts["person_id"].to_i
@company_id = opts["company_id"].to_i
end
def self.all
results = DB.exec("SELECT * FROM jobs;")
return results.map { |result| Job.new(result) }
end
def self.find(id)
results = DB.exec("SELECT * FROM jobs WHERE id=#{id};")
return Job.new(results.first)
end
def self.create(opts={})
results = DB.exec(
<<-SQL
INSERT INTO jobs (person_id, company_id)
VALUES ( #{opts["person_id"]}, #{opts["company_id"]} )
RETURNING id, person_id, company_id;
SQL
)
return Job.new(results.first)
end
def self.delete(id)
results = DB.exec("DELETE FROM jobs WHERE id=#{id};")
return { deleted: true }
end
def self.update(id, opts={})
results = DB.exec(
<<-SQL
UPDATE jobs
SET person_id=#{opts["person_id"]}, company_id=#{opts["company_id"]}
WHERE id=#{id}
RETURNING id, person_id, company_id;
SQL
)
return Job.new(results.first)
end
end

@ -21,4 +21,10 @@ Rails.application.routes.draw do
post '/locations/:id/inhabitants', to: 'people#create' post '/locations/:id/inhabitants', to: 'people#create'
post '/people/:id/home', to: 'locations#create' post '/people/:id/home', to: 'locations#create'
get '/jobs', to: 'jobs#index'
get '/jobs/:id', to: 'jobs#show'
post '/jobs', to: 'jobs#create'
delete '/jobs/:id', to: 'jobs#delete'
put '/jobs/:id', to: 'jobs#update'
end end

Loading…
Cancel
Save