IanI
IanI

Reputation: 370

creating singular resources in jsonapi-resources

Using the jsonapi-resources gem (and Rails 4), I'm attempting to create a singular (or singleton) resource (not supplying the id on the url for the standard show, update and delete requests), in my case for a profile of the current (logged in) user, so I can do a 'GET /profiles' rather than a 'GET /profiles/:id'.

I've added the singular route to the config/routes.rb file:

jsonapi_resource :profiles

as per the documents https://github.com/cerebris/jsonapi-resources#jsonapi_resource

So how do I modify the resource (ProfileResource) to map the id to the current_user (via the context)?

the existing demo apps do not demonstrate using the singular resource, and there doesn't seemed to be any documentation that (explicitly) address this.

Upvotes: 3

Views: 562

Answers (2)

IanI
IanI

Reputation: 370

That works! (thks)

the key for me was

config/routes.rb

jsonapi_resource :profile

and in the app/resources/profile_resource.rb

def self.find_by_key(key, options = {})
  model = options[:context][:current_user]
  fail JSONAPI::Exceptions::RecordNotFound.new(key) if model.nil?
  new(model, options[:context])
end

and then hitting(GET,PUT,POST,DELETE) '/profile' works fine.

Upvotes: 1

galiat
galiat

Reputation: 54

In your Profile resource, you can override the self.find_by_key method to instantiate via the user stored in the context, if the key is 'me'. For current user, you could hit /profiles/me.

def self.find_by_key(key, options = {})
  new(options[:context][:current_user], options[:context]) if key == 'me'
end

Upvotes: 1

Related Questions