Delete a resource from external API from destroy action in Rails controller?

313 Views Asked by At

I'm figuring out how can I delete some resource from an external API from destroy action in Rails controller.

to delete this resource I have to do this, actually I have this code in a Concern in controllers folder:

Concern

def unsubscribe_user
  @external_api = ExternalApi.new(@key1, @key2)

  @subscription = @external_api.create(:subscription)
  # subscription_id and client_id are stored in my DB as an "historical" record
  @unsubscribed = @subscription.delete(subscription_id, client_id)
end

Controller

def destroy
  unsubscribe_user

  if @unsubscribed.nil?
      flash[:notice] = "Successfully unsubscribed..."
      redirect_to root_path
    else
      flash[:error] = "An error has ocurred..."
      redirect_to root_path
    end
end

sooo, in my view I have:

<p>Unsubscribe <%= button_to "Cancel my Subscription", suscription_path, {:action => :delete} %> </p>

Rails needs an ID to delete a resource from DB (for example: subscription_path(current_user.id)), so, I don't have this resource in my local DB, there is no ID to pass. I only need to execute this Concern code in the destroy action. How can I do that?

Edit

I forget to put routes:

resources :subscribe, except: :edit
2

There are 2 best solutions below

1
teddylee On

just use a fake id like 1, or you can use some other route config for this action

0
Vedant Agarwala On

Use the singular resource in your routes:

resource :subscribe, except: :edit

Then in your rake routes you can see that you don't need an id argument