Skip to content

Return existing object on create #432

@thomassnielsen

Description

@thomassnielsen

We've got a use case (for backwards compatibility) that requires us to return an existing object in certain cases when the client runs a create (POST) request.

As far as I can tell, this is neither explicitly allowed or forbidden by the JSONAPI spec.

Our current workaround is to override self.create on the resource and detect if the client will accept an existing object or not:

def self.create(context)
  if context[:controller].params["data"]["attributes"]["status"] == 'makeme'
    # Try to find existing order. Create a resource instance with this order if we find one.
    order = Order.find_by status: 'draft', user: context[:current_user]
    return new(order, context) if order.present?
  elsif context[:controller].params["data"]["attributes"]["status"] == 'makenew'
    # Try to find existing order. Set it to status stalled if we find it.
    order = Order.find_by status: 'draft', user: context[:current_user]
    if order.present?
      order.status = 'stalled'
      order.save!
    end
  end
  super context
end

This works, except that we want the resource to be returned untouched. Using this method, the resource tries to update the resource with the data from the POST request (which we don't want in this case). Is there a better way to do this?

I know this is a very specific use case, but I wonder if there is or could be a point to override that would make this a bit cleaner. Something like returning a resource that behaves like it was called with a show operation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions