diff --git a/app/controllers/fruits_controller.rb b/app/controllers/fruits_controller.rb index cdb7008..a43833f 100644 --- a/app/controllers/fruits_controller.rb +++ b/app/controllers/fruits_controller.rb @@ -1,4 +1,6 @@ class FruitsController < ApplicationController + skip_before_action :verify_authenticity_token + def index # render({ :json => { :message => 'hi', :status => 200 } }) # render json: message: 'hi', status: 200 # doesn't work because nested objects are unguessable @@ -8,4 +10,8 @@ class FruitsController < ApplicationController def show render json: Fruit.find(params[:id]) end + + def create + render json: Fruit.create(params["fruit"]) + end end diff --git a/app/models/fruit.rb b/app/models/fruit.rb index 00b5ec8..04f32be 100644 --- a/app/models/fruit.rb +++ b/app/models/fruit.rb @@ -5,7 +5,7 @@ class Fruit else DB = PG.connect(host: "localhost", port: 5432, dbname: 'simplerails') end - + def initialize(opts = {}) @id = opts["id"].to_i @name = opts["name"] @@ -22,4 +22,9 @@ class Fruit results = DB.exec("SELECT * FROM fruits WHERE id=#{id};") return Fruit.new(results.first) end + + def self.create(opts={}) + results = DB.exec("INSERT INTO fruits (name, color, readytoeat) VALUES ( '#{opts["name"]}', '#{opts["color"]}', #{opts["readyToEat"]} );") + return Fruit.new(opts) + end end diff --git a/config/routes.rb b/config/routes.rb index da1a659..598e466 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -3,4 +3,5 @@ Rails.application.routes.draw do get '/fruits', to: 'fruits#index' # get('/fruits', { :to => 'fruits#index' }) get '/fruits/:id', to: 'fruits#show' + post '/fruits', to: 'fruits#create' end