Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 AbstractController::Metal rendering with status != 200 (i.e. 401, 404)

I'm implementing a simple API in my application to communicate with an Android application. I'm trying to use AbstractController::Metal mainly for performance. The problem I'm having is that render is ignoring the status option that I'm passing.

Very simple example:

class Api::V1::ApiController < ActionController::Metal
  include AbstractController::Rendering
  include ActionController::Renderers::All
  include ActionController::RackDelegation
  include ActionController::MimeResponds
end

class Api::V1::SessionsController < Api::V1::ApiController
  def show
    render status: :unauthorized   # using 401 yields the same result
  end
end

Calling

curl -v -X GET http://app.dev:3000/api/v1/sessions.json

I'd expect to receive a 401 but instead I get a 200 OK:

> GET /api/v1/sessions.json HTTP/1.1
> User-Agent: curl/7.30.0
> Host: app.dev:3000
> Accept: */*
> 
< HTTP/1.1 200 OK

Any ideas? Overwriting response.status is the only work around I've found so far, but honestly it looks like an ugly hack.

Thank you in advance for your insights.

like image 917
Felipe Koch Avatar asked Aug 27 '14 15:08

Felipe Koch


People also ask

How can you tell Rails to render without a layout?

By default, if you use the :plain option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option and use the . text. erb extension for the layout file.

What does render JSON do in Rails?

By using render json: in our Rails controller, we can take entire models or even collections of models, have Rails convert them to JSON, and send them out on request.

How do you render a partial?

Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html.


1 Answers

To render nothing and return code 401 use:

render nothing: true, status: :unauthorized
like image 178
Kamen Kanev Avatar answered Nov 15 '22 21:11

Kamen Kanev