Fix query in ToolsController

pull/826/head
Rick Carlino 2018-05-02 14:33:08 -05:00
parent a2989cc46c
commit 5d314b61cc
3 changed files with 35 additions and 14 deletions

View File

@ -1,14 +1,5 @@
module Api
class ToolsController < Api::AbstractController
INDEX_QUERY = 'SELECT
"tools".*,
points.id as tool_slot_id
FROM
"tools"
LEFT OUTER JOIN
"points" ON "points"."tool_id" = "tools"."id"
WHERE
"tools"."device_id" = %s;'
def index
render json: tools
@ -39,11 +30,11 @@ private
end
def tools
Tool.find_by_sql(INDEX_QUERY % current_device.id)
@tools ||= Tool.outter_join_slots(current_device.id)
end
def tool
@tool ||= Tool.where(device: current_device).find(params[:id])
@tool ||= Tool.join_tool_slot_and_find_by_id(params[:id])
end
end
end

View File

@ -2,10 +2,32 @@
# confused with Peripherals, which keep track of electronic data such as pin
# modes.
class Tool < ApplicationRecord
BASE = 'SELECT
"tools".*,
points.id as tool_slot_id
FROM
"tools"
LEFT OUTER JOIN
"points" ON "points"."tool_id" = "tools"."id"
WHERE'
INDEX_QUERY = BASE + ' "tools"."device_id" = %s;'
SHOW_QUERY = BASE + ' "tools"."id" = %s;'
IN_USE = "Tool in use by the following sequences: %s"
belongs_to :device
has_one :tool_slot
validates :device, presence: true
validates :name, uniqueness: { scope: :device }
IN_USE = "Tool in use by the following sequences: %s"
def self.outter_join_slots(device_id)
self.find_by_sql(INDEX_QUERY % device_id)
end
def self.join_tool_slot_and_find_by_id(id)
# Adding the || self.find part to raise 404 like "normal" AR queries.
# TODO: Clean this whole thing up - RC 2-may-18
self.find_by_sql(SHOW_QUERY % id).first || self.find(id)
end
end

View File

@ -3,12 +3,11 @@ module Devices
RESOURCES = [ :device_configs, :farm_events, :images, :logs, :peripherals,
:pin_bindings, :plant_templates, :points, :regimens,
:saved_gardens, :sensor_readings, :sensors, :sequences,
:token_issuances, :tools, :users, :webcam_feeds ]
:token_issuances, :users, :webcam_feeds ]
required { model :device, class: Device }
def execute
output = { device: device.body_as_json }
RESOURCES.each do |name|
model = device.send(name)
output[name] = \
@ -16,5 +15,14 @@ module Devices
end
output
end
private
def output
@output ||= {
device: device.body_as_json,
tools: Tool.outter_join_slots(device.id).map(&:body_as_json)
}
end
end
end