What HTTP method should a route have if it's for create_or_delete

58 Views Asked by At

Yea I know it's such a strange purpose create_or_delete. But I have an attendances table for users, and in the frontend there's a checkbox,

  • when it's checked -> create an attendance record
  • when unchecked -> delete the attendance record

Attendances table is created such that, when a user attends on a day, a record is created. When a user is absent on a specific date, there will be no record for that date.

And on the admin side, there's a checkbox under the specific date, to change the attendance status.

For some business needs, I can't have a boolean is_attended or something similar.

So my question is, for the below route, what method should be on it? the once I can think of the most is PUT but not sure about the delete part.

Or should the frontend handle that in the first place, such that:

  • when checkbox is checked it sends POST request to create attendance
  • when it's unchecked it sends DELETE request to delete attendance
def create_or_delete
    attendance = Attendance.find_by(date: attendance_params[:date], user_id: attendance_params[:user_id])
    if attendance
      delete_attendance attendance
    else
      create_attendance attendance
    end
  end

  private
  def attendance_params
    params.require(:attendance).permit(:date ,:user_id)
  end

  def create_attendance(attendance)
    attendance = Attendance.new(attendance_params)
    if attendance.save
      render json: { message: "Attendance updated", status: 200 }, status: :ok
    else
      render json: { errors: attendance.errors, status: 422 }, status: :unprocessable_entity
    end
  end

  def delete_attendance(attendance)
    if attendance.destroy
        render json: { message: "Attendance updated", status: 200 }, status: :ok
      else
        render json: { errors: "Failed updating attendance", status: 422 }, status: :unprocessable_entity
      end
  end
1

There are 1 best solutions below

0
Bruno Costanzo On

The best option is to stay on CRUD routes. So you can handle the attendance state un the UI and just point to different routes in any case. If the attendance status is just a boolean attribute in a model and not a record that you delete or create, you could have a toggle_attendance :put action, or stay with the CRUD sending the complete object to the classic :update route.