:destroy

General Setup & Layout

Notes
  1. Local Handling: This is where you'd place role-based or permission-based checks to ensure that the current user has the required privileges to delete the specified item. It can also host any other checks or preparations that you'd like to perform before attempting to delete the item.

  2. Abstracted/Reusable Handling: You might want to have some logging or auditing concerns that log every deletion for audit trail purposes. Or perhaps there are additional operations/extensions that you'd like to perform before or after the item is destroyed. Those can be laid out here.

  3. Execute & Respond: This section is where the actual action is performed (deletion of the item) and where the system prepares its response to the client based on the outcome. If the deletion was successful, a success message is sent; otherwise, an error is conveyed.

Example Setup:

class ItemsController < ApplicationController
  before_action :set_item, only: [:destroy]

  def destroy

    # LOCAL HANDLING
    ##################

    # Role-based or permission-based check
    unless @current_user_role == "admin" || @item.created_by == @current_user.id
      return render json: { error: 'Permission denied' }, status: :forbidden
    end

    # Additional checks or preparations if any
    # ...

    
    # ABSTRACTED/REUSABLE HANDLING (e.g. Concerns, etc.)
    ##################
    
    # CONCERNS
    # Maybe some logging or auditing before deletion
    # ...

    # OTHER
    # Additional operations or extensions
    # ...


    # EXECUTE & RESPOND
    ##################
    
    if @item.destroy
      render json: { message: 'Item successfully deleted' }
    else
      render json: { error: 'Failed to delete item' }, status: :unprocessable_entity
    end
    
  end

  # ... Other actions ...

  private

  def set_item
    @item = Item.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    render json: { error: 'Item not found' }, status: :not_found
  end
end

Last updated