I'm using Jsonapi-resource for my Rails API. I have a User
model which has a boolean account_manager
as an attribute. I want to have a separate controller/endpoints for the account managers.
The index action should return all users that are account managers and sanitize the data to only return the id
, first_name
and last_name
.
I have an AccountManagerResource
and AccountManagerController
. But the index action errors due to @model
being nil in my resource. Does anyone know if I'm missing anything?
class JsonApiBaseResource < JSONAPI::Resource
abstract
relationship :customer, to: :one
before_create do
@model.customer_id = context[:current_customer].id
end
filter :updated_since,
verify: -> (value, _context) {
value.map{ |value| value.to_i }
},
apply: -> (records, value, _options) {
records.updated_since(Time.at(value[0]))
}
def self.records(options = {})
current_customer(options).public_send(@model.to_s.tableize).ordered
end
def self.current_customer(options)
options[:context][:current_customer]
end
end
UserResource
class UserResource < JsonApiBaseResource
attributes :title, :first_name, :last_name, :email, :company_name,
:job_title, :telephone_number, :user_type
relationship :account_manager, to: :one
relationship :company, to: :one
relationship :roles, to: :many
relationship :asset_permissions, to: :many
paginator :paged_with_all
before_create do
if current_user = context[:current_user]
@model.created_by_admin = current_user.super_admin?
end
end
filter :search,
apply: -> (records, value, _options) {
records.search(value[0])
}
filter :user_type
filter :roles
filter :company
filter :account_manager
end
Account Manager Resource
class AccountManagerResource < JsonApiBaseResource
abstract
attributes :id, :first_name, :last_name
model_name 'User'
end
Account Manager Controller
class AccountManagersController < JsonApiBaseController
apipie_concern_subst(resource: 'Account Manger')
include CrudActions
skip_before_action :authenticate_user, only: [:index]
resource_description do
description <<-EOS
- **type** = users
### Attributes
- **id**: *number*
- **first-name**: *string*
- **last-name**: *string*
EOS
end
api! "Returns all Account Manager names"
def index
super
end
end
The error I get is unique to my particular project but it is a result of @model
being nil when raised in JsonApiBaseResource
on the call to the index action of the AccountManagerController
.
Any help would be much appreciated.