V
V
vadimstroganov2015-10-22 19:07:05
Ruby on Rails
vadimstroganov, 2015-10-22 19:07:05

How to render a method with a status?

Hello!
There is a call_404 method

render :json => Error::call_404, status: :not_found

How to make it so that you do not write status all the time?
status: :not_found
I would like to set it once in the call_404 method, so that each time I do not write status in the controllers.
Is this possible?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zaporozhchenko Oleg, 2015-10-22
@vadimstroganov

We usually do something like this. Adding methods to the base controller

def respond_with_400(exception)
    render json: { success: false, all_errors: ['The user has not authorized application'] }, status: 400
  end

  def respond_with_404(exception=nil)
    render json: { success: false, all_errors: [t('errors.not_found')] }, status: 404
  end

  def respond_with_500(exception)
    render json: {success: false, all_errors: [t('errors.something_went_wrong')], debug: exception.to_s}, status: 500
  end

  def respond_with_success(resource=nil, status=200)
    result = {success: true}
    result.merge!(:"#{resource.class.name.underscore}" => {id: resource.id}) if resource.present?

    render json: result, status: status
  end

  def respond_with_errors(resource=nil, status=422, debug=nil)
    result = {success: false}

    result.merge!(errors: resource.errors.messages, all_errors: resource.errors.full_messages)  if resource.present?
    result.merge!(debug: debug) if debug.present?

    render json: result, status: status
  end

C
CapeRatel, 2015-10-22
@CapeRatel

There is nothing wrong with writing a status. Visualization in the code is good (not to be confused with "hardcode").
If you really really need it, make separate methods and indicate the status in them. And then just call the desired method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question