JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources

Help with endpoint for a non-ActiveRecord model without a database table

Open
#1,092 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
2.3k
Forks
546
PR merge metrics
No merged PRs in 30d

Description

I have a non-ActiveRercord model without a database table I am trying to create an API endpoint for. The data for this model is populated dynamically with custom SQL and provides generic relations to real ActiveRecords.

Because of all the magic happening with JSONAPI Resources I am having a hard time serializing the array of ActiveModels successfully. Am wondering what the best approach for this might be? I've tried some monkey patching without success and would appreciate guidance

model example

class CalendarEvent
  include ActiveModel::Model

  attr_accessor(
    :id,
    :title,
    # etc etc
  )

  def self.modelize(record)
    return CalendarEvent.new(record)
  end

  def self.records(person_id, start_date, end_date, options = {})
    sql = "select 'some custom sql' from various_table where serious_magic_happens"
    records = ActiveRecord::Base.connection.execute(sql)
    records = records.map{ |r| self.modelize(r) } # returns an Array of CalendarEvent::Class
  end

end

controller attempt

class Api::V3::CalendarEventsController < Api::V3::ApiController

  def index
    records = CalendarEvent.records(1686, '2017-07-01', '2017-07-31')
    resources = records.map { |r| Api::V3::CalendarEventResource.new(r, nil) }
    JSONAPI::ResourceSerializer.new(Api::V3::CalendarEventResource).serialize_to_hash(resources)
  end

end

The above controller returns a 204 No Content even though I am passing serialize_to_hash an array ... am I misunderstanding how this should work ? Or is there a better way?

Thanks!

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the CalendarEvent model example and Api::V3::CalendarEventsController, then trace how JSONAPI::ResourceSerializer handles the mapped ActiveModel array. Reproduce the 204 No Content response and inspect the resource and serializer behavior for non-ActiveRecord models. Done means identifying a supported serialization approach or documenting the required integration changes.

Written by the indexing model from the issue text.

Assessment

Tech stack
rails, ruby
Domain
api, backend
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.