I am trying to use Rail's Serializer on a JSON object being returned by an API in a Rails API app. I need to authenticate, ingest the API, filter the data, and rebroadcast the filtered data. No view is required.
To filter the data, I am trying to implement the Serializer - it's clear I haven't set it up correctly though. I can see it is working and in place because it is adding the initial object in front of the data it is returning (see data below: serialized object starts with kobo_data). But it is returning all the fields of data, not just the fields I'm trying to call. In this case I'm trying to return just the field prikey, but it is returning all the fields of data.
I've tried to address issues in similar threads to this (ActiveModel::Serializer in Rails - serializer methods ignored in JSON result, rails active model serializer not doing anything, Using ActiveModel::Serializer in Rails - JSON data differs between json and index response), although since I don't have a .html view, I wonder if this might be related to the issue mentioned in the last link. But another tutorial I"ve done (https://thesocietea.org/2015/03/building-a-json-api-with-rails-part-2-serialization/) employs serialization in a Rails-API app without a view, so I'm guessing it's not.
Any suggestions on what I'm doing wrong and how I can fix it?
Model:
class KoboApi < ActiveRecord::Base
require 'rest_client'
USERNAME = ENV['KOBO_API_USER']
PASSWORD = ENV['KOBO_API_PWD']
SURVEY = ENV['KOBO_API_SURVEY']
# API_BASE_URL = "https://kc.kobotoolbox.org/api/v1/"
API_BASE_URL = "https://sg.smap.com.au/api/v1"
def self.get_api_info
uri = "#{API_BASE_URL}/data/#{SURVEY}?format=json"
rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)
response = rest_resource.get
JSON.parse response
end
end
Controller
class KoboDataController < ApplicationController
def index
@kobo_info = KoboApi.get_api_info
render json: @kobo_info
end
end
Application Controller
class ApplicationController < ActionController::API
include ActionController::Serialization
end
kobo_api_serializer.rb
class KoboApiSerializer < ActiveModel::Serializer
attributes :prikey
end
Gem file
source 'https://rubygems.org'
gem 'active_model_serializers', '~> 0.8.3'
gem 'rest-client'
gem 'pg'
gem 'rails', '4.2.5.1'
gem 'rails-api'
gem 'spring', :group => :development
# gem for environment variables
gem 'dotenv-rails', :groups => [:development, :test]
gem 'figaro'
Data returned
{"kobo_data":[{"prikey":"1","Upload Time":"2016-06-17 11:11:38.802+00","Version":"1","Complete":"t","Survey Notes":"","Location Trigger":"","deviceid":"webworm"....[data truncated]
uninitialized constant KoboDataController::ActiveModelSerializerserror. - Mugshep