Search code examples
ruby-on-railssingletonjsonapi-resources

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.


Solution

  • 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