glinda93
glinda93

Reputation: 8459

Rails: how to halt request cycle in API only application?

Consider this example in the official doc:


class ApplicationController < ActionController::Base
  before_action :require_login
 
  private
 
  def require_login
    unless logged_in?
      flash[:error] = "You must be logged in to access this section"
      redirect_to new_login_url # halts request cycle
    end
  end
end

redirect_to makes no sense in api-only application. How can I halt request cycle and respond with custom json or 401 code in API only applications with filters?

Upvotes: 1

Views: 774

Answers (2)

rmlockerd
rmlockerd

Reputation: 4136

As @Josh's answer says, calling render causes Rails to create a response body and terminate the request cycle. By default the HTTP response code is 200, but you can use the :status option to specify a different HTTP response code:

class ApplicationController < ActionController::Base
  before_action :require_login
 
  private
 
  def require_login
    unless logged_in?
      render json: 'Unauthorized', status: 401
    end
  end
end

Rails also supports a set of pre-defined symbols instead of numerical codes so status: :unauthorised is the same as status: 401. Check the documentation for a list of supported symbols.

Upvotes: 1

Josh Brody
Josh Brody

Reputation: 5363

Just doing a render should suffice:

class PostsController < ActionController::API # or ApplicationController
  before_action :halt_request

  def index  
    render json: "bravemaster"
  end 

  private 


  def halt_request
    if params[:halt]
      render json: "I stopped"
    end     
  end
end

If ActionController detects a response body being set in a callback it will return.

Upvotes: 3

Related Questions