0 votes
in Ruby by

Which code would you add to return a 404 to the API caller if the user is not found in the database?

class UsersController < ApplicationController

  def show

    @user = User.find(params[:id])

    render json: @user, status: :ok,

    # Missing code

end

 A.

rescue => e

  logger.info e

end

 B.

rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response

 C.

rescue ActiveRecord::RecordNotFound

  render json: { message: 'User not found' }, status: :not_found

end

 D.

raise ActiveRecord::RecordNotFound

  render json: { message: 'User not found' }, status: :user_not_found

end

1 Answer

0 votes
by

Which code would you add to return a 404 to the API caller if the user is not found in the database?

class UsersController < ApplicationController

  def show

    @user = User.find(params[:id])

    render json: @user, status: :ok,

    # Missing code

end

Correct answer is :- rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response

Related questions

0 votes
asked Sep 3, 2022 in Ruby by DavidAnderson
0 votes
asked Sep 2, 2022 in Ruby by DavidAnderson
...