Skip to content

Override create to return existing object

Thomas Sunde Nielsen edited this page Sep 16, 2015 · 1 revision

Some times one might want to return an existing object instead of creating a new one under certain conditions.

This can be done in several ways, including overriding create on the controller:

In this case, we want to return any existing order with status draft if we ask the server to makeme, while we always want to return a new order if the status is makenew.

We start by checking the incoming status, and when it's one of the two we want to override, we some custom work. Otherwise, we call super to let JR do it's thing.

def create
  case params[:data][:attributes][:status]
  when 'makeme'
    order = Order.find_by status: 'draft', user: current_user
    if order.present?
      @request.operations = [] # Remove create operation
      params[:id] = order.id
      @request.setup_show_action params
    end
  when 'makenew'
    order = Order.find_by status: 'draft', user: current_user
    if order.present?
      order.status = 'stalled'
      order.save
    end
  end
  super
end