Class: DevicesController

Inherits:
ApplicationController show all
Defined in:
app/controllers/devices_controller.rb

Instance Method Summary collapse

Methods inherited from ApplicationController

#render_not_found_response

Instance Method Details

#createObject


19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'app/controllers/devices_controller.rb', line 19

def create
    device = Device.new(device_params)
    begin
        device.save
    rescue ActiveRecord::NotNullViolation => exception
        render json: { status: 'ERROR', message: 'Saving failed: Missing deviceName value', data: exception.message }, status: :unprocessable_entity
    rescue ActiveRecord::InvalidForeignKey => exception
        render json: { status: 'ERROR', message: 'Saving failed: user_id does not exist', data: exception.message }, status: :not_found
    rescue ActiveRecord::RecordNotUnique => exception
       render json: { status: 'ERROR', message: 'Saving failed: device_id already exists', data: exception.message }, status: :unprocessable_entity
    else
        render json: { status: 'SUCCESS', message: "Device saved", data: device }, status: :ok
    end
end

#destroyObject


44
45
46
47
48
49
50
51
52
# File 'app/controllers/devices_controller.rb', line 44

def destroy
    device = Device.find_by(device_id: params[:id])
    if device
        device.destroy
        render json: { status: "SUCCESS", message: "Device deleted", data: device }, status: :ok
    else 
        render json: { status: "ERROR", message: "No device found for requested user" }, status: :not_found
    end
end

#indexObject


5
6
7
8
# File 'app/controllers/devices_controller.rb', line 5

def index
    devices = Device.all
    render json: { status: "SUCCESS", message: "All devices currently in DB", data: devices }, status: :ok
end

#showObject


10
11
12
13
14
15
16
17
# File 'app/controllers/devices_controller.rb', line 10

def show
    devices = Device.find_by(user_id: params[:user_id])
    if devices
        render json: { status: "SUCCESS", message: "All devices currently assigned to requested user", data: devices }, status: :ok
    else
        render json: { status: "ERROR", message: "No device found for requested user" }, status: :not_found
    end
end

#updateObject


34
35
36
37
38
39
40
41
42
# File 'app/controllers/devices_controller.rb', line 34

def update
    device = Device.find_by(device_id: params[:id])
    if device
        device.update_attributes(device_params)
        render json: { status: "SUCCESS", message: "Device updated", data: device }, status: :ok
    else
        render json: { status: "ERROR", message: "No device found for requested user" }, status: :not_found
    end
end