简体   繁体   中英

Where vs Find in Rails Api

Let's say I have a student Rails API which having an endpoint that looks like http://www.example.com/students/1

What is the preferred way to implement?

review = Review.find(inputs[:review_id])
To handle exceptions,
rescue_from Exception, :with => :internal_error
def internal_error(e)
 render json: {error: {message: "Internal Error"} }, :status => 500
end

OR

review = Review.where(inputs[:review_id]).first
if review.nil?
 render json: {error: {message: "Internal Error"} }, :status => 500
end

My question is which is better way for handling non-existent id through the url.

You should go with the first approach

# reviews_controller.rb
review = Review.find(inputs[:review_id])

And

# application_controller.rb

# rescue_from Exception, :with => :internal_error

# OR Prefer ActiveRecord::RecordNotFound

rescue_from ActiveRecord::RecordNotFound, :with => :internal_error # Prefer this one

def internal_error(e)
  render json: {error: {message: "Internal Error"} }, :status => 500
end

To make it generic, Add it to application_controller.rb

NOTE:

  • This way you don't have to rescue it in every controller (the second approach you have to)

You can add a global rescue_from in your base controller ( ApplicationController for example) and then use the find method (Best way to retrieve only one record) :

  rescue_from ActiveRecord::RecordNotFound do |e|
    render status: :not_found, json: { error: { message: e.message } }
  end

Every time you try to retrieve a record, if he doesn't exist you will render an error message and a 404 status which stand for a non-existent resource.

Neither. You can just do something like:

unless review = Review.find_by(id: inputs[:review_id])
  render json: {error: {message: "record not found"} }, status: :not_found
end

Benefits:

  1. Does't require endless nil checking as mentioned in comments.
  2. Avoids unnecessary exception handling.
  3. Returns a more informative error message.

You should use rescue for manage error

def action_name
  review = Review.find(inputs[:review_id])
  render json: review, status: :ok
  rescue # for ever not found
  render json: {}, status: :not_found,nothing: true
end

doc for status list

and you can use rescue_from on header but this works for every action

rescue_from ActiveRecord::RecordNotFound,with: action_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM